// ==UserScript==
// @name          Yahoo TV Listings Enhancer
// @description   Enhances Yahoo TV listings (tv.yahoo.com)
// @namespace     http://www.gozer.org/mozilla/greasemonkey/
// @include       http://tv.yahoo.com/grid/*
// ==/UserScript==

// originally / inspired by / converted from:
//   http://userscripts.org/scripts/show/3379
//   rchandran@gmail.com

function GM_yahooTvEnhancer_findPosX(e)
{
  var x = 0;

  if(e.offsetParent) {
    while(e.offsetParent) {
      x += e.offsetLeft
      e = e.offsetParent;
    }
  } else if(e.x)
    x += e.x;

  return(x);
}

function GM_yahooTvEnhancer_findPosY(e)
{
  var y = 0;

  if(e.offsetParent) {
    while(e.offsetParent) {
      y += e.offsetTop
      e = e.offsetParent;
    }
  } else if(e.y)
    y += e.y;

  return(y);
}

document.body.addEventListener('click',
  function(e)
  {
    var s = document.getElementById('myahgm');

    if(s && s.style.display == 'block')
      s.style.display = 'none';

    if(!(e.target.nodeName == 'A' && e.target.href.indexOf('progutn') != -1))
      return;

    e.stopPropagation();
    e.preventDefault();

    if(!s) {
      var n = 'position: absolute;' +
              'background: #aaccaa;' +
              'border: 1px solid #000;' +
              'left: 0; top: 0;' +
              'width: 300px;' +
              'padding: 5px;' +
              'overflow: hidden;' +
              'display: none;';

      s = document.createElement('div');
      s.setAttribute('id', 'myahgm');
      s.setAttribute('style', n);

      document.body.appendChild(s);
    }

    GM_xmlhttpRequest({
      method: 'GET',
      url: e.target.href,
      onload: function(req)
      {
        s = document.getElementById('myahgm');
        s.style.display = 'none';

        var text = req.responseText;

        var start = text.indexOf('<div class="tabContainer">');

        text = text.substring(start+26);

        // tv show
        var end = text.indexOf('<div class="futureEpisodes">');

        // movie or other
        if(end < 0)
          end = text.indexOf('</p>');

        text = text.substring(0, end);

        // remove tivo text and link
        text = text.replace(/<p>.*TiVo./, '')
                   .replace(/<a class="small".* more...<\/a>/, '');

        s.innerHTML = text;
        s.style.left = GM_yahooTvEnhancer_findPosX(e.target);
        s.style.top = GM_yahooTvEnhancer_findPosY(e.target);
        s.style.display = 'block';
      }
    });
  }, true);
