// ==UserScript==
// @name           AllegroTools (Clock) for IE i FF
// @namespace      http://allegrotoolsie.hopto.org/
// @description    Dodaje odliczajacy w tyl zegar na aukcjach Allegro // v0.20090505.0
// @include        http*://*allegro.pl/item*
// @include        http*://*allegro.pl/show_item.php?*
// ==/UserScript==

var endTime = null;
var liveClock = null;


/////////////////////////////////////////////////////////////////
//// IE/FF compatibility
/////////////////////////////////////////////////////////////////

// In FF childNodes returns also #text nodes that represents
// the whitespaces in the HTML source. IE skips these nodes
// For IE and FF use this method instead od childNodes property
// to return all children of an element.
// NOTE: this method skips ALL #text nodes (not only whitespaces)
function getChildNodes(element)
{
  var children = new Array();

  if(element)
  {
    var child = element.firstChild;
    while(child)
    {
      if (child.nodeType == 1)
      {
        children.push(child);
      }
      child = child.nextSibling;
    }
  }

  return children;
}

// In FF firstChild returns also #text nodes that represents
// the whitespaces in the HTML source. IE skips these nodes
// For IE and FF use this method instead of firstChild property
// to return the first non-#text element.
// NOTE: this method skips ALL #text nodes (not only whitespaces)
function getFirstChild(element)
{
  var child = element.firstChild;
  while(child && (child.nodeType != 1))
  {
    child = child.nextSibling;
  }
  
  return child;
}

// Returns the number-th next sibling of the element
// for IE/FF compatibility skips #text nodes
function getNextSibling(element, number)
{
  var sibling = element;
  while((number > 0) && (sibling))
  {
    sibling = sibling.nextSibling;
    if (sibling && (sibling.nodeType == 1))
    {
      number--;
    }
  }
  
  return sibling;
}

// FF uses textContent property while IE uses innerText property
// to return the inner text of an element
function getInnerText(element)
{
  var result = null;
  
  if (element)
  {
    // For IE
    result = element.innerText;
  
    if(result == null)
    {
      // For FireFox
      result = element.textContent;
    }
  }
  
  return result;
}

// IE specific functions
function select()
{
  if (arguments.length>1) {
    var node = arguments[0];
    for (var i=1; i<arguments.length; i++) {
      if (typeof(arguments[i])=='string') {
        node = node.getElementById(arguments[i]);
      } else {
        var nodeIdx = arguments[i];
        var children = getChildNodes(node);
        if (nodeIdx<children.length) {
          node = children[nodeIdx];
        } else {
          node = null;
          break;
        }
      }
    }
  }
  return node;
}

/**
 * pobiera date konca aukcji
 */
function CLOCK_getEndTime(str)
{
  if(str.match(/(<span class=.?small.?>\(.{3} \d{2} .{3} \d{4} \d{2}:\d{2}:\d{2} .+?\)<\/span>)/ig))
  {
    
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

/**
 * zamienia string allegrowej daty w date JS
 */
function CLOCK_makeDate(str)
{
  var PATTERN = new Array('sty','lut','mar','kwi','maj','cze','lip','sie','wrz','pa\u017A','lis','gru');
  var REPLACE = new Array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct',     'nov','dec');
  var data = str.match(/\d{2} .{3} \d{4} \d{2}:\d{2}:\d{2} /g)[0];

  for (var i = 0; i < PATTERN.length; i++)
  {
    data = data.replace(PATTERN[i], REPLACE[i]);
  }

  return Date.parse(data);
}

/**
 * Date.prototype
 * liczy czas od tej daty (this) do danej innej, wyjscie formatuje
 */
Date.prototype.CLOCK_timeTo = function(otherdate)
{
  var delta = otherdate - this;
  return new CLOCK_TimeTo(delta);
}

/**
 *
 */
function CLOCK_TimeTo(miliseconds)
{
  this.negative = (miliseconds < 0);
  this.miliseconds = Math.abs(miliseconds);
  this.s = Math.floor(this.miliseconds / 1000) % 60;
  this.m = Math.floor(this.miliseconds / 1000 / 60) % 60;
  this.h = Math.floor(this.miliseconds / 1000 / 60 / 60) % 24;
  this.d = Math.floor(this.miliseconds / 1000 / 60 / 60 / 24);
}

CLOCK_TimeTo.prototype.toString = function()
{
  var str = "";
  if(this.d > 0)
  {
    str = this.d + "d " + this.h + "h " + this.m + "m " + this.s + "s";
  }
  else if(this.h > 0)
  {
    str = this.h + "h " + this.m + "m " + this.s + "s";
  }
  else if(this.m > 0)
  {
    str = this.m + "m " + this.s + "s";
  }
  else
  {
    str = this.s + "s";
  }
  
  if(this.negative)
  {
    str = "Zakonczona " + str + " temu";
  }
  else if (this.miliseconds < (1000 * 60 * 10))
  {
    str = "<font color='#ff0000'>" + str + "</font>";
  }
  
  return str;
}  

function findClockElement()
{
  var clockElement = null;
  var pagecontent = document.getElementById("pagecontent1");

  if(pagecontent)
  {
    var descriptionTableBody = select(pagecontent, 0, 3, 0, 0, 0, 0, 0);
    if(descriptionTableBody)
    {
      var tdArray = descriptionTableBody.getElementsByTagName("TD");
      if(tdArray)
      {
        for(var i = 0; i < tdArray.length; i++)
        {
          if(tdArray[i].innerHTML.match(/Do ko.ca/))
          {
            clockElement = getNextSibling(tdArray[i], 1);
            break;
          }
        }
      }
    }  
  }

  return clockElement;
}

function replaceClock(clockElement)
{
  var oldClock = getFirstChild(clockElement);
  if(oldClock)
  {
    var newClock = document.createElement("B");
    newClock.innerHTML = oldClock.innerHTML;
    clockElement.replaceChild(newClock, oldClock);
    return newClock;
  }  
}

function updateClock()
{
  var now = new Date();
  liveClock.innerHTML = now.CLOCK_timeTo(endTime);
  setTimeout(updateClock, 1000);
}

function allegrotoolsClock()
{
  var clockElement = findClockElement();
  if(clockElement)
  {
    var endTimeStr = CLOCK_getEndTime(clockElement.innerHTML);
    if(endTimeStr)
    {
      endTime = CLOCK_makeDate(endTimeStr);
      liveClock = replaceClock(clockElement);
      updateClock();
    }  
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Start Allegro Tools (Clock) script
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
allegrotoolsClock()

