// ==UserScript==
// @name         pwnlast.fm
// @namespace    http://pwnlast.fm/
// @include      http://www.last.fm/music/*
// @include      http://www.lastfm.*/music/*
// @include      http://cn.last.fm/music/*
// @exclude      http://www.last.fm/music/*/*
// @exclude      http://www.lastfm.*/music/*/*
// @exclude      http://cn.last.fm/music/*/*
// @include      http://isohunt.com/forum/pwn/*
// @description  Torrent links in the last.fm pages
// @author       Nikita Vasilev
// @version      0.2
// @licence      MIT
// ==/UserScript==

(function(){


  if (document.location.href.indexOf('http://isohunt.com/forum/pwn/direct_link') == 0) {
    var direct_link = document.location.pathname.match(RegExp('direct_link/(.+)'))[1];
    if (typeof direct_link == 'string') {
      document.location.replace(direct_link);
    }
    return
  }


  /**
   * 'Nirvana' and 'Michael+Jackson' are examples
   * @type String
   */
  var artist_name = document.location.pathname.match(RegExp('music/([^/]+)/?$'))[1];
  if (!artist_name) {
    return;
  }


  /**
   * 'http://isohunt.com/js/json.php?ihq=Nirvana' and 'http://isohunt.com/js/json.php?ihq=Michael+Jackson' are examples
   * @type String
   * @link http://isohunt.com/forum/viewtopic.php?p=433527&sid=#433527
   */
  var url = 'http://isohunt.com/js/json.php?ihq='+ artist_name;


  // Workaround for non-greasemonkey compatible browsers (Opera, maybe Chrome)
  if (typeof GM_addStyle == 'undefined') {
    /**
     * GM_addStyle('* {color:red}') is an example
     * @param css String
     */
    window.GM_addStyle = function (css) {
      var heads = document.evaluate('//head',document,null,XPathResult.ANY_TYPE,null);
      var head = heads.iterateNext();
      if (head) {
        var style = document.createElement("style");
        style.type = "text/css";
        style.appendChild(document.createTextNode(css));
        head.appendChild(style);
      };
    };
  }


  GM_addStyle(
    '#torrent_search_block {}\
     #torrent_search_block h2.heading .h2Wrapper {padding-bottom:0; margin-bottom:-.5em;}\
     #torrent_search_block table {text-align:right; table-layout:fixed;}\
     #torrent_search_block thead td.playbuttonCell {width:17px;}\
     #torrent_search_block td {white-space:nowrap;}\
     #torrent_search_block .subjectCell {text-align:left; width:80%;}\
     #torrent_search_block .subjectCell a {display:inline-block; width: 100%; vertical-align:top; width:100%; overflow:hidden;}\
     #torrent_search_block td.play,\
     #torrent_search_block td.download {width:1.6em; padding-left:0; padding-right:0;}\
     #torrent_search_block td.size {width:4em;}\
     #torrent_search_block td.size small {font-size:9px; color:#666; margin-left:2px}\
     #torrent_search_block td.seeds,\
     #torrent_search_block td.leechers {width:2.5em;}\
     #torrent_search_block td.play a,\
     #torrent_search_block td.download a {opacity:.3; text-decoration:none; padding: 0 .3em;}\
     #torrent_search_block td.play a:hover,\
     #torrent_search_block td.download a:hover {opacity:1;}'
  );


  if (typeof JSON == 'undefined') {
    window.JSON = {};
    /**
     * JSON.parse('{"forty two": "42"}')  // {"forty two": 42}
     * @param json_string String
     */
    JSON.parse = function(json_string) {
      return eval('('+ json_string +')');
    };
  }


  /**
   * Box for torrent search result
   */
  var catalogueHead = document.getElementById('catalogueHead');
  var torrent_search_block = document.createElement('div');
  torrent_search_block.id = 'torrent_search_block';
  catalogueHead.parentNode.insertBefore( torrent_search_block, catalogueHead.nextSibling );
  torrent_search_block.innerHTML = '<h2 class="heading"><span class="h2Wrapper"><a class="icon" href="http://isohunt.com/torrents/'+ artist_name +'">\
    Torrents from Isohunt</a></span></h2>';


  /**
   * Direct links fix
   * Isohunt doesn't allow links to torrent files from another sites. Fix it.
   */
  var iframe = document.createElement('iframe');
  iframe.src = 'http://isohunt.com/forum/pwn/please_allow_direct_links_for_torrents';
  iframe.name = 'isohunt_direct_links_fix';
  iframe.style.display = 'none';
  document.body.appendChild(iframe);


  /**
   * Send crossdomain AJAX request to isohunt
   */
  var expand_torrent_search = function expand_torrent_search () {
    if (typeof GM_xmlhttpRequest != 'undefined') {
      GM_xmlhttpRequest({
        method: 'GET',
        url: url +'&rows=15',
        headers: {
          'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
          'Accept': 'text/json'
        },
        onload: function(response) {
          if (response && response.statusText == 'OK') {
            var json = JSON.parse(response.responseText);
            var str = '<table class="chart"><thead><tr><td class="playbuttonCell"></td><td class="subjectCell"></td><td class="download"></td><td class="size">Size</td><td title="Seeds" class="seeds">S</td><td title="Leechers" class="leechers">L</td></tr></thead><tbody>';
            for (var i=0; i<json.items.list.length; i++) {
              str += '<tr '+ ((i&1)==0 ? 'class="odd"' : '') +'>' +
                     '<td class="playbuttonCell">'+
                       (parseInt(json.items.list[i].Seeds) ? '<a href="http://www.bitlet.org/music/play?torrent='+ encodeURIComponent(json.items.list[i].enclosure_url) +'"><img width="17" height="17" src="http://cdn.last.fm/flatness/clear.gif" alt="▶" class="icon play_icon"/></a>' : '')
                     + '</td>' +
                     '<td class="subjectCell"><a href="' + json.items.list[i].link + '">' + json.items.list[i].title + '</a></td>' +
                     '<td class="download"><a target="isohunt_direct_links_fix" href="http://isohunt.com/forum/pwn/direct_link/' + json.items.list[i].enclosure_url +'">▼</a></td>' +
                     '<td class="size">' + parseInt(Math.round(parseFloat(json.items.list[i].size))) + '<small>MB</small></td>' +
                     '<td class="seeds">' + json.items.list[i].Seeds + '</td>' +
                     '<td class="leechers">' + json.items.list[i].leechers + '</td></tr>';
            }
            str += '</tbody></table>';
            torrent_search_block.innerHTML += str;
          } else {
            torrent_search_block.innerHTML += '<span class="error">'+ response.statusText + ' ('+ response.status +')</span>';
          }
        }
      });
    } else if (window.opera) {
      throw new Error("Opera doesn't supported yet :-(");
    } else {
      throw new Error("Can't accomplish GM_xmlhttpRequest. Seems like Greasemonkey for Firefox is not installed.");
    }
  };
  expand_torrent_search();

})();

