// $Id: VideoURLs.user.js 6 2006-11-07 21:06:21Z jesse $
//
// VideoURLs Greasemonkey script.
// Author: Jesse Merriman <jessemerriman@warpmail.net>
//
// ==UserScript==
// @name          VideoURLs
// @namespace     http://www.jessemerriman.com/
// @description   Finds URLs to videos in JavaScript, and adds real links.
// @include *
// ==/UserScript==

// Fun with regular expressions. There are probably some odd cases that I
// am currently missing though.. There always are..
const starters =       '(?:"|\\\'|)';
const protocols =      '(?:(?:http|ftp)://)';
const urlChars =       '(?:[0-9a-zA-Z/\\.\\+\\=\\&\\~\\-_]+)';
const videoPostfixes = '(?:\\.(?:avi|mpeg|mpg|wmv))';
const enders =         '(?:&|"|\\\'|)';

const urlRegex =
    new RegExp(
        '.*\\=' + starters +
        '(' + protocols + urlChars + videoPostfixes + ')' +
        enders + '.*');

// Add an element as the last child of the body.
function addToBody(element) {
    document.body.insertBefore(element, document.body.lastChild.nextSibling);
}

// Find and return all video URLs embedded in <script> tag text.
function findVideoURLs(elements) {
    var videoURLs = new Array();
    for (var i = 0; i < elements.length; i++) {
        if (match = urlRegex.exec(elements[i].text)) {
            videoURLs.push(match[1]);
        }
    }
    return videoURLs;
}

// Add links to the given URLs at the bottom of the page.
function addLinks(urls) {
    // If there are any URLs, add some space before the links.
    if (urls.length > 0) {
        var spacer = document.createElement('br');
        addToBody(spacer);
    }

    // Actually add the links to the bottom of the page.
    for (var i = 0; i < urls.length; i++) {
        var link = document.createElement('a');
        link.href = urls[i];
        link.innerHTML = '~~~~Video URL ' + (i+1) + '~~~~';
        addToBody(link);
    }
}

var allScriptNodes = document.getElementsByTagName('script');
var urls = findVideoURLs(allScriptNodes);
addLinks(urls);

