// Greasemonkey http://greasemonkey.mozdev.org/
//
// ==UserScript==
// @name           Media Matters Direct 1.0
// @description    Adds direct links to download embedded media.
// @namespace      http://deoxy.org/gm
// @include        http://mediamatters.org*
// @include        http://*.mediamatters.org*
// ==/UserScript==

(function() {
  var siteurl = 'http://mediamatters.org';
  var loc = location.href;
  var videodiv;
  var done = 0;
  
  var divs = document.getElementsByTagName('div');
  if (divs) {
    for (var i = 0; i < divs.length; i++) {
      if (i == 3) {
        videodiv = divs[i];
        audiodiv = divs[i];
        break;
      }
    }
  }  
  var embed   = document.getElementsByTagName('embed');
  var scripts = document.getElementsByTagName('script');
  if (scripts && scripts[1]) {
    var videourl;
    var js = scripts[1].innerHTML;
    if (js) {
    var lines = js.split('\n'); 
    for (var i = 0; i < lines.length; i++) {
      if (lines[i].match(/^var/)) {
        videourl = lines[i].replace(/^.*?"([^"]+)"\);$/,'$1');
        videourl = siteurl + videourl;
        if (videodiv) {
          var text = document.createElement('a');
          text.setAttribute('href',  videourl);
          text.setAttribute('title', videourl);
          var ext = videourl.replace(/^.*?\.([^\.]+)$/,'$1');
          text.appendChild(document.createTextNode('[download '+ext+']'));
          videodiv.appendChild(text);
          done = 1;
          break;
        }
      }
    }
    }
  }
  if (embed && done == 0) {  
    for (var i = 0; i < embed.length; i++) {
      var audiourl = embed[i].getAttribute('src');
      audiourl = siteurl + audiourl;
      var text = document.createElement('a');
      text.setAttribute('href',  audiourl);
      text.setAttribute('title', audiourl);
      var ext = audiourl.replace(/^.*?\.([^\.]+)$/,'$1');
      text.appendChild(document.createTextNode('[download '+ext+']'));
      audiodiv.appendChild(text);
    }
  }
})();

