// ==UserScript==
// @name           AllegroTools (komentarze) dla IE
// @namespace      http://www.allegrotoolsie.hopto.org/
// @description    Dodatkowe narzedzia pomocne przy przegladaniu komentarzy uzytkownikow Allegro // v0.20070113.2
// @include        http*://*allegro.pl/show_user.php?*
// @include        http*://*allegro.pl/my_allegro.php?page=feedbacks
// @include        http*://*allegro.pl/my_allegro.php?*page=feedbacks*type=fb_recvd*
// @include        http*://*allegro.pl/my_allegro.php?*page=feedbacks*type=fb_gave*
// @exclude        http*://*allegro.pl/*no_limit=1*
// ==/UserScript==

var SELLER_COLORS = new Array("#FFD9C6", "#FFE8DD");
var BUYER_COLORS = new Array("#C6D9FF", "#DDE8FF");

var SELLER_STRING = "Sprzedaj";
var BUYER_STRING = "Kupuj";
var POSITIVE_STRING = "Pozytywny";
var NEUTRAL_STRING = "Neutralny";
var NEGATIVE_STRING = "Negatywny";

var ALL_BTN = "_all_btn_";
var SELLERS_BTN = "_sellers_btn_";
var BUYERS_BTN = "_buyers_btn_";
var CHECK_LINKS_BTN = "_check_links_btn_";
var COLORING_CHBX = "_coloring_chkbx_";
var AUTOCHECK_CHBX = "_autocheck_chkbx_";
var COMMENTS_ALL_BTN = "_comments_all_btn_";
var COMMENTS_POSITIVE_BTN = "_comments_positive_btn_";
var COMMENTS_NEUTRAL_BTN = "_comments_neutral_btn_";
var COMMENTS_NEGATIVE_BTN = "_comments_negative_btn_";

var COMMENT_TABLE_BODY = false;
var COMMENTS = new Array();

var BG_BYSTR = "data:image/png;base64,"+
     "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAFRlDm/AAAAB3RJTUUH1gwHDRgVt4pvywAAAAlw"+
     "SFlzAAAPYQAAD2EBqD+naQAAAARnQU1BAACxjwv8YQUAAAAYSURBVHjaY/j/nwEGoEwQBWEyoovD"+
     "FQMAkc0N9HFYUnUAAAAASUVORK5CYII=";

var showCommentTypeFilter = false;

/////////////////////////////////////////////////////////////////
// Utility 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 = node.childNodes;
        if (nodeIdx<children.length) {
          node = children[nodeIdx];
        } else {
          node = null;
          break;
        }
      }
    }
  }
  return node;
}

function registerEventHandler(element, eventName, handler)
{
  if (element.addEventListener)
  {
    element.addEventListener(eventName, handler, false);
  }
  else if (document.attachEvent)
  {
    element.attachEvent("on" + eventName, handler);
  }
} 

/////////////////////////////////////////////////////////////////
// Event handlers section
/////////////////////////////////////////////////////////////////
function handleCommentsAllButton()
{
  enableButton(COMMENTS_ALL_BTN, false);
  GM_setValue("AT_C_comment_type_filter", COMMENTS_ALL_BTN);
  filterComments();
  enableButton(COMMENTS_POSITIVE_BTN, true);
  enableButton(COMMENTS_NEUTRAL_BTN, true);
  enableButton(COMMENTS_NEGATIVE_BTN, true);
}

function handleCommentsPositiveButton()
{
  enableButton(COMMENTS_POSITIVE_BTN, false);
  GM_setValue("AT_C_comment_type_filter", COMMENTS_POSITIVE_BTN);
  filterComments();
  enableButton(COMMENTS_ALL_BTN, true);
  enableButton(COMMENTS_NEUTRAL_BTN, true);
  enableButton(COMMENTS_NEGATIVE_BTN, true);
}

function handleCommentsNeutralButton()
{
  enableButton(COMMENTS_NEUTRAL_BTN, false);
  GM_setValue("AT_C_comment_type_filter", COMMENTS_NEUTRAL_BTN);
  filterComments();
  enableButton(COMMENTS_ALL_BTN, true);
  enableButton(COMMENTS_POSITIVE_BTN, true);
  enableButton(COMMENTS_NEGATIVE_BTN, true);
}

function handleCommentsNegativeButton()
{
  enableButton(COMMENTS_NEGATIVE_BTN, false);
  GM_setValue("AT_C_comment_type_filter", COMMENTS_NEGATIVE_BTN);
  filterComments();
  enableButton(COMMENTS_ALL_BTN, true);
  enableButton(COMMENTS_POSITIVE_BTN, true);
  enableButton(COMMENTS_NEUTRAL_BTN, true);
}

function handleAllButton()
{
  enableButton(ALL_BTN, false);
  GM_setValue("AT_C_filter", ALL_BTN);
  filterComments();
  enableButton(SELLERS_BTN, true);
  enableButton(BUYERS_BTN, true);
}

function handleSellersButton()
{
  enableButton(SELLERS_BTN, false);
  GM_setValue("AT_C_filter", SELLERS_BTN);
  filterComments();
  enableButton(ALL_BTN, true);
  enableButton(BUYERS_BTN, true);
}

function handleBuyersButton()
{
  enableButton(BUYERS_BTN, false);
  GM_setValue("AT_C_filter", BUYERS_BTN);
  filterComments();
  enableButton(ALL_BTN, true);
  enableButton(SELLERS_BTN, true);
}

function handleCheckLinksButton()
{
  enableButton(CHECK_LINKS_BTN, false);
  checkLinks();
}

function handleColoringCheckbox()
{
  var coloring = getCheckbox(COLORING_CHBX);
  GM_setValue("AT_C_coloring", coloring);
  filterComments();
}

function handleAutocheckCheckbox()
{
  var autocheck = getCheckbox(AUTOCHECK_CHBX);
  GM_setValue("AT_C_autocheck", autocheck);
  showButton(CHECK_LINKS_BTN, !autocheck);
  autocheckLinks();
}

/////////////////////////////////////////////////////////////////
// Links checking related functions
/////////////////////////////////////////////////////////////////
function getEndTime(str){
  if(str.match(/<span class="small">\((.{3} \d{2} .{3} \d{4} \d{2}:\d{2}:\d{2} .+?)\)<\/span>/))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

function getTitle(str)
{
  if(str.match(/<div.*?>\s*?(.+?) <span class="nobold">\(numer \d+?\)<\/span>\s*?<\/div>/))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

function getTitleExternal(str)
{
  if(str.match(/<li class="title"><h3>(.+?)<\/h3><\/li>/))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

function getPrice(str)
{
  if(str.match(/<tr>\s*?<td.*?>(Cena <span class="textBN">Kup Teraz<\/span>:|Aktualna cena)<\/td>\s*?<td.*?><b>(.*?)<\/b>.*?\s*?<\/td>\s*?<\/tr>/))
  {
    return RegExp.$2;
  }
  else
  {
    return null;
  }
}

function checkExternalArchive(str)
{
  if(str.match(/Aukcja <span class="black">nr \d*?<\/span> nie widnieje w naszej bazie/g))
  {
    return false;
  }
  else
  {
    return true;
  }
}

function autocheckLinks()
{
  if(isEnabledButton(CHECK_LINKS_BTN) && getCheckbox(AUTOCHECK_CHBX))
  {
    handleCheckLinksButton();
  }
}

function checkLinks()
{
  if (COMMENTS)
  {
    for(var i = 0; i < COMMENTS.length; i++)
    {
      new LinkChecker(COMMENTS[i]);
    }
  }
}

function LinkChecker(row)
{
  if(row)
  {
    var link = select(row, 3, 0);
    if(link)
    {
      this.row = row;
      this.link = link;
      this.linkTD = link.parentNode;
      this.checkLink();
    }
  }
}

function addTitle(row, titleHTML)
{
  var titleSpan = document.createElement('span');
  titleSpan.style.fontSize = '8pt';
  titleSpan.style.color = '#606060';
  titleSpan.innerHTML = titleHTML;
  var text = select(row, 0, 0);
  text.parentNode.insertBefore(titleSpan, text.parentNode.lastChild.nextSibling);
}

LinkChecker.prototype.mark = function()
{
  this.linkTD.style.backgroundImage = "url('"+BG_BYSTR+"')";
}

LinkChecker.prototype.unmark = function()
{
  this.linkTD.style.backgroundImage = "";
}

LinkChecker.prototype.checkLink = function()
{
  this.allegroUrl = this.link.getAttribute("href");
  this.mark();
  var me = this;
  GM_xmlhttpRequest({method:"GET", url:this.allegroUrl, onload:function(d){me.processCheckLinkResponse(d)}});
}

LinkChecker.prototype.processCheckLinkResponse = function(details)
{
  var responseText = details.responseText;
  var endTime = getEndTime(responseText);
  if (endTime)
  {
    var linkSpan = document.createElement('span');

    linkSpan.innerHTML = endTime + "<br>";
    this.link.parentNode.insertBefore(linkSpan, this.link);

    var title = getTitle(responseText);
    var price = getPrice(responseText);
    addTitle(this.row, "<br><b>" + title + " - " + price +"</b>");

    this.unmark();
  }
  else
  {
    this.checkArchiverLink(); 
  }
}

LinkChecker.prototype.checkArchiverLink = function()
{
  this.archiverUrl = "http://www.allegro.archiver.pl/search.php?itid=" + this.link.innerText;
  var me = this;
  GM_xmlhttpRequest({method:"GET", url:this.archiverUrl, onload:function(d){me.processCheckArchiverLinkResponse(d)}});
}

LinkChecker.prototype.processCheckArchiverLinkResponse = function(details)
{
  var responseText = details.responseText;
  var isInExternalArchive = checkExternalArchive(responseText);
  var linkSpan = document.createElement('span');
  if (isInExternalArchive)
  {
    linkSpan.innerHTML = "Archiwum zewnetrzne<br>";
    this.link.href = "http://www.allegro.archiver.pl/search.php?itid=" + this.link.innerText;
    this.link.setAttribute("target", "_blank");

    var title = getTitleExternal(responseText);
    if(title)
    {
      addTitle(this.row, "<br><b>" + title +"</b> (archiwum zewnetrzne)");
    }
    else
    {
      addTitle(this.row, "<br>Brak aukcji w archiwum Allegro. Zaloguj sie na <a href='http://www.allegro.archiver.pl'>www.allegro.archiver.pl</a> aby wyswietlic tytul");
    }
  }
  else
  {
    linkSpan.innerHTML = this.link.innerText;
    this.link.style.display = "none";
  }
  this.unmark();
  this.link.parentNode.insertBefore(linkSpan, this.link);
}

/////////////////////////////////////////////////////////////////
// Coment filtering/coloring related functions
/////////////////////////////////////////////////////////////////
function changeCommentRowBackgroundColor(element, color, doColoring)
{
  var newColor = doColoring ? color : "";
  for(var i=0; i<element.childNodes.length; i++)
  {
    element.childNodes[i].style.backgroundColor = newColor;
  }
  element.nextSibling.firstChild.style.backgroundColor = newColor;
}

function hideComment(row, hide)
{
  if (row)
  {
    var displayValue = hide ? "none" : "block";
    row.style.display = displayValue;
    row.nextSibling.style.display = displayValue;
  }
}

function filterComments()
{
  if(COMMENTS)
  {
    var filter  = GM_getValue("AT_C_filter", ALL_BTN);
    var commentTypeFilter  = GM_getValue("AT_C_comment_type_filter", COMMENTS_ALL_BTN);
    var doColoring = GM_getValue("AT_C_coloring", false);
    var hideSellers = (filter == BUYERS_BTN);
    var hideBuyers = (filter == SELLERS_BTN);
    var hidePositive = ((commentTypeFilter != COMMENTS_ALL_BTN) && (commentTypeFilter != COMMENTS_POSITIVE_BTN) && showCommentTypeFilter);
    var hideNeutral = ((commentTypeFilter != COMMENTS_ALL_BTN) && (commentTypeFilter != COMMENTS_NEUTRAL_BTN) && showCommentTypeFilter);
    var hideNegative = ((commentTypeFilter != COMMENTS_ALL_BTN) && (commentTypeFilter != COMMENTS_NEGATIVE_BTN) && showCommentTypeFilter);
    var id = false;
    var hide  = false;
    var visibleCount = 0;
    var color = false;
    for(var i = 0; i < COMMENTS.length; i++)
    {
      id = COMMENTS[i].getAttribute("id");
      hide = false;
      
      // Check seller/buyer
      if (id.match(SELLER_STRING))
      {
        hide = hideSellers;
        color = SELLER_COLORS[visibleCount % 2];
      }  
      else if (id.match(BUYER_STRING))
      {
        hide = hideBuyers;
        color = BUYER_COLORS[visibleCount % 2];
      }

      // Check positive/neutral/negative
      if (id.match(POSITIVE_STRING))
      {
        hide = (hide || hidePositive);
      }  
      else if (id.match(NEUTRAL_STRING))
      {
        hide = (hide || hideNeutral);
      }  
      else if (id.match(NEGATIVE_STRING))
      {
        hide = (hide || hideNegative);
      }

      // If row displayed - do coloring
      if(hide == false)
      {
        changeCommentRowBackgroundColor(COMMENTS[i], color, doColoring)
        visibleCount++;
      }

      hideComment(COMMENTS[i], hide);
    }
  }
}

/////////////////////////////////////////////////////////////////
// Menu related functions
/////////////////////////////////////////////////////////////////
function showButton(id, show)
{
  var displayValue = show ? "block" : "none";
  var element = document.getElementById(id);
  if(element && element.style.display != displayValue)
  {
    element.style.display = displayValue;
  }
}

function enableButton(id, enable)
{
  var element = document.getElementById(id);
  if(element && element.disabled != !enable)
  {
    element.disabled = !enable;
  }
}

function isEnabledButton(id)
{
  var element = document.getElementById(id);
  if(element)
  {
    return !element.disabled;
  }
  else
  {
    return false;
  }
}

function setCheckbox(id, checked)
{
  var element = document.getElementById(id);
  if(element && element.checked != checked)
  {
    element.checked = checked;
  }
}

function getCheckbox(id)
{
  var element = document.getElementById(id);
  if(element)
  {
    return element.checked;
  }
  else
  {
    return false;
  }
}

function getButtonHtml(title, help, id, visible)
{
  return "<td><input style=\"font-size=8pt\" title=\"" + help + "\" type=\"button\" id=\"" + id + "\" value=\"" + title +"\"/></td>";
}

function getCheckboxHtml(title, help, id)
{
  return "<td><input style=\"font-size=8pt\" title=\"" + help + "\" type=\"checkbox\" id=\"" + id + "\"/><label style=\"font-size=8pt\" title=\"" + help + "\" for=\"" + id + "\">" + title + "</label></td>";
}

function addMenu()
{
  if(showCommentTypeFilter)
  {
    var commentTypeFilter  = GM_getValue("AT_C_comment_type_filter", COMMENTS_ALL_BTN);
    var filterCommentTypeMenu = document.createElement("div");
    filterCommentTypeMenu.innerHTML = "<table cellspacing=2 cellpadding=0 border=0>" +
                     getButtonHtml("Wszystkie", "Wyswietla wszystkie komentarze", COMMENTS_ALL_BTN, true) +
                     getButtonHtml("Pozytywne", "Wyswietla tylko komentarze pozytywne", COMMENTS_POSITIVE_BTN, true) +
                     getButtonHtml("Neutralne", "Wyswietla tylko komentarze neutralne", COMMENTS_NEUTRAL_BTN, true) +
                     getButtonHtml("Negatywne", "Wyswietla tylko komentarze negatywne", COMMENTS_NEGATIVE_BTN, true) +
                     "</tr></table>";
    COMMENT_TABLE_BODY.parentNode.parentNode.insertBefore(filterCommentTypeMenu, COMMENT_TABLE_BODY.parentNode);
    enableButton(COMMENTS_ALL_BTN, (commentTypeFilter != COMMENTS_ALL_BTN));
    enableButton(COMMENTS_POSITIVE_BTN, (commentTypeFilter != COMMENTS_POSITIVE_BTN));
    enableButton(COMMENTS_NEUTRAL_BTN, (commentTypeFilter != COMMENTS_NEUTRAL_BTN));
    enableButton(COMMENTS_NEGATIVE_BTN, (commentTypeFilter != COMMENTS_NEGATIVE_BTN));
    registerEventHandler(document.getElementById(COMMENTS_ALL_BTN), "click", handleCommentsAllButton);
    registerEventHandler(document.getElementById(COMMENTS_POSITIVE_BTN), "click", handleCommentsPositiveButton);
    registerEventHandler(document.getElementById(COMMENTS_NEUTRAL_BTN), "click", handleCommentsNeutralButton);
    registerEventHandler(document.getElementById(COMMENTS_NEGATIVE_BTN), "click", handleCommentsNegativeButton);
  }

  var filter  = GM_getValue("AT_C_filter", ALL_BTN);
  var coloring = GM_getValue("AT_C_coloring", false);
  var autocheck = GM_getValue("AT_C_autocheck", false);
  var filterBuyerSellerMenu = document.createElement("div");
  filterBuyerSellerMenu.innerHTML = "<table cellspacing=2 cellpadding=0 border=0>" +
                   getButtonHtml("Wszyscy", "Wyswietla kupujacych i sprzedajacych", ALL_BTN, true) +
                   getButtonHtml("Sprzedajacy", "Wyswietla tylko sprzedajacych", SELLERS_BTN, true) +
                   getButtonHtml("Kupujacy", "Wyswietla tylko kupujacych", BUYERS_BTN, true) +
                   "<td>&nbsp;</td>" +
                   getCheckboxHtml("Kolorowanie", "Wlacza/wylacza kolorowanie kupujacych/sprzedajacych", COLORING_CHBX) +
                   "<td>&nbsp;</td>" +
                   getCheckboxHtml("Autosprawdzanie", "Wlacza/wylacza automatyczne sprawdzanie aukcji. Najpierw sprawdzane jest archiwum Allegro, jesli aukcja nie zostanie znaleziona sprawdzane jest archiwum zewnetrzne www.allegro.archiver.pl. Gdy wlaczona jest ta opcja, przycisk sprawdz aukcje jest niedostepny", AUTOCHECK_CHBX) +
                   "<td>&nbsp;</td>" +
                   getButtonHtml("Sprawdź aukcje", "Sprawdza aukcje wyswietlane na tej stronie. Najpierw sprawdzane jest archiwum Allegro, jesli aukcja nie zostanie znaleziona sprawdzane jest archiwum zewnetrzne www.allegro.archiver.pl. Jesli przycisk ten jest wylaczony, oznacza to ze aukcje na tej stronie zostaly juz sprawdzone lub sprawdzanie jest w toku", CHECK_LINKS_BTN) +
                   "</tr></table>";
  COMMENT_TABLE_BODY.parentNode.parentNode.insertBefore(filterBuyerSellerMenu, COMMENT_TABLE_BODY.parentNode);
  enableButton(ALL_BTN, (filter != ALL_BTN));
  enableButton(SELLERS_BTN, (filter != SELLERS_BTN));
  enableButton(BUYERS_BTN, (filter != BUYERS_BTN));
  showButton(CHECK_LINKS_BTN, !autocheck);
  setCheckbox(COLORING_CHBX, coloring);
  setCheckbox(AUTOCHECK_CHBX, autocheck);
  registerEventHandler(document.getElementById(ALL_BTN), "click", handleAllButton);
  registerEventHandler(document.getElementById(SELLERS_BTN), "click", handleSellersButton);
  registerEventHandler(document.getElementById(BUYERS_BTN), "click", handleBuyersButton);
  registerEventHandler(document.getElementById(CHECK_LINKS_BTN), "click", handleCheckLinksButton);
  registerEventHandler(document.getElementById(COLORING_CHBX), "click", handleColoringCheckbox);
  registerEventHandler(document.getElementById(AUTOCHECK_CHBX), "click", handleAutocheckCheckbox);
}

/////////////////////////////////////////////////////////////////
function findComments()
{
  var tables = document.getElementsByTagName("table");
  var commentRows = false;
  // First find tables with comments
  for (var i = 0; i < tables.length; ++i)
  {
    node = tables[i];
    classAttr = node.getAttribute('className');
    if((classAttr) && (classAttr == "list-head"))
    {
      COMMENT_TABLE_BODY = node.firstChild;
      commentRows = COMMENT_TABLE_BODY.childNodes;
      break;
    }
  }
  
  // Now group seller and buyer comments also mark positive/neutral/negative comments
  if (commentRows)
  {
    var row, cell, commentTypeCell;
    // Skip first row - table header
    for(var i=1; i < commentRows.length; i++)
    {
      row = commentRows[i];
      if(row && (row.childNodes.length > 1)) // check length to skip comment text rows
      {
        cell = row.firstChild;
        commentTypeCell = select(row, 1, 0);
        if(cell && commentTypeCell)
        {
          var string = cell.innerText;
          var commentTypeString = commentTypeCell.innerText;
          var id = false;
          // TODO correct matching strings
          if(string.match(SELLER_STRING))
          {
            id = SELLER_STRING;
          }  
          else if(string.match(BUYER_STRING))
          {
            id = BUYER_STRING;
          }

          if(commentTypeString.match(POSITIVE_STRING))
          {
            id = id.concat(POSITIVE_STRING);
          }
          else if(commentTypeString.match(NEUTRAL_STRING))
          {
            id = id.concat(NEUTRAL_STRING);
          }
          else if(commentTypeString.match(NEGATIVE_STRING))
          {
            id = id.concat(NEGATIVE_STRING);
          }

          row.setAttribute("id", id);
          COMMENTS.push(row);
        }
      }
    }
  }
}

function allegrotoolsComments()
{
  if(document.location.href.match(/type=fb_gave_usr/) ||
    (document.location.href.match(/page=feedbacks/) && document.location.href.match(/type=fb_gave/)) ||
    (document.location.href.match(/page=feedbacks/) && document.location.href.match(/type=fb_recvd/)) ||
    (document.location.href.match(/page=feedbacks/) && (document.location.href.match(/type/) == null)))
  {
    showCommentTypeFilter = true;
  }
  findComments();
  filterComments();
  addMenu();
  autocheckLinks();
}

/////////////////////////////////////////////////////////////////
// Start Allegro Tools Comments script
/////////////////////////////////////////////////////////////////

allegrotoolsComments()
