// ==UserScript==
// @name           AllegroTools (komentarze) dla IE i FF
// @namespace      http://www.allegrotoolsie.hopto.org/
// @description    Dodatkowe narzedzia pomocne przy przegladaniu komentarzy uzytkownikow Allegro // v0.200700314.0
// @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*
// @include        http*://*allegro.pl/my_allegro.php?*page=feedbacks*type=fb_add*
// @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 = false;
var COMMENTS = new Array();

var BG_BYSTR = "data:image/png;base64,"+
     "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAFRlDm/AAAAB3RJTUUH1gwHDRgVt4pvywAAAAlw"+
     "SFlzAAAPYQAAD2EBqD+naQAAAARnQU1BAACxjwv8YQUAAAAYSURBVHjaY/j/nwEGoEwQBWEyoovD"+
     "FQMAkc0N9HFYUnUAAAAASUVORK5CYII=";

var showCommentTypeFilter = false;
var isAddFeedbackPage = 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 = getChildNodes(node);
        if (nodeIdx<children.length) {
          node = children[nodeIdx];
        } else {
          node = null;
          break;
        }
      }
    }
  }
  return node;
}

// 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;
}

/////////////////////////////////////////////////////////////////
//// IE/FF compatibility
/////////////////////////////////////////////////////////////////

// FF uses addEventListener method while IE uses attachEvent method
// to register event handler
// Call this mehod with the element that generates the event,
// the event name (without 'on' prefix) and the handler routine
// The handler routine should accept an event source
// See getEvent method to see how to get the event source in FF and IE
function registerEventHandler(element, eventName, handler)
{
  if (element.addEventListener)
  {
    element.addEventListener(eventName, handler, false);
  }
  else if (document.attachEvent)
  {
    element.attachEvent("on" + eventName, handler);
  }
} 

// 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 of 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;
}

// 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;
}

// 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;
}

/////////////////////////////////////////////////////////////////
// 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 getTitleOld(str)
{
  if(str.match(/<td class=cellwhite-tr-f><a href=\"\/item\d+?.*?.html\">(.*?)<\/a>\s*?<\/td>/))
  {
    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 checkError(str)
{
  if(str.match(/<table.*?class="table-error".*?>/g))
  {
    return true;
  }
  else
  {
    return false;
  }
}

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)
  {
    this.row = row;

    var link = false;
    // Don't check auction link on add feedback page
    if (isAddFeedbackPage == false)
    {
      link = select(row, 3, 0);
    }

    if(link)
    {
      this.link = link;
      this.linkTD = link.parentNode;
      this.checkLink();
    }

    var commentLink = false;
    if (isAddFeedbackPage)
    {
      commentLink = select(row, 3, 0);
    }
    else
    {
      commentLink = select(row, 4, 0);
    }
    
    if(commentLink)
    {
      this.commentLink = commentLink;
      this.commentLinkTD = commentLink.parentNode;
      this.checkCommentLink();
    }
  }
}

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);
  // We care about #text nodes here so lastChild/nextSibling
  // methods are used instead of getLastChild/getNextSibling IE/FF compatibility methods
  text.parentNode.insertBefore(titleSpan, text.parentNode.lastChild.nextSibling);
}

LinkChecker.prototype.mark = function(element)
{
  if (element)
  {
    if(element.markCount)
    {
      element.markCount += 1;
    }
    else
    {
      element.markCount = 1;
      element.style.backgroundImage = "url('"+BG_BYSTR+"')";
    }
  }
}

LinkChecker.prototype.unmark = function(element)
{
  if (element)
  {
    if(element.markCount && element.markCount > 1)
    {
      element.markCount -= 1;
    }
    else
    {
      element.markCount = 0;
      element.style.backgroundImage = "";
    }
  }
}

LinkChecker.prototype.checkLink = function()
{
  this.allegroUrl = this.link.href;
  this.mark(this.linkTD);
  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>");
  }
  else
  {
    this.auctionNumber = getInnerText(this.link);
    this.checkArchiverLink(); 
    this.checkAllegroOldLink();
  }
  this.unmark(this.linkTD);
}

LinkChecker.prototype.checkArchiverLink = function()
{
  this.archiverUrl = "http://www.allegro.archiver.pl/search.php?itid=" + this.auctionNumber;
  this.mark(this.linkTD);
  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 = this.archiverUrl;
    this.link.setAttribute("target", "_blank");
    this.link.parentNode.insertBefore(linkSpan, this.link);
  }
  else
  {
    linkSpan.innerHTML = this.auctionNumber;
    this.link.style.display = "none";
  }

  this.link.parentNode.insertBefore(linkSpan, this.link);
  this.unmark(this.linkTD);
}

LinkChecker.prototype.checkAllegroOldLink = function()
{
  this.allegroOldUrl = "http://allegro.pl/my_allegro.php?page=feedbacks&type=us_data&item_id=" + this.auctionNumber;
  this.mark(this.linkTD);
  var me = this;
  GM_xmlhttpRequest({method:"GET", url:this.allegroOldUrl, onload:function(d){me.processCheckAllegroOldLinkResponse(d)}});
}

LinkChecker.prototype.processCheckAllegroOldLinkResponse = function(details)
{
  var titleOld = getTitleOld(details.responseText);
  var linkSpan = document.createElement('span');
  if (titleOld)
  {
    if (titleOld != this.auctionNumber)
    {
      addTitle(this.row, "<br><b>" + titleOld +"</b>");
    }
    else
    {
      addTitle(this.row, "<br>Tytul aukcji niedostepny</b>");
    }
  }
  else
  {
    addTitle(this.row, "<br>Aby sprobowac odnalezc i wyswietlic tytul aukcji <a href='http://allegro.pl/my_allegro.php?mm=1' target='_blank'>zaloguj sie na Allegro</a> a nastepnie odswiez te strone");
  }
  this.unmark(this.linkTD);
}

LinkChecker.prototype.checkCommentLink = function()
{
  this.commentLinkUrl = this.commentLink.href;
  this.mark(this.commentLinkTD);
  var me = this;
  GM_xmlhttpRequest({method:"GET", url:this.commentLinkUrl, onload:function(d){me.processCheckCommentLinkResponse(d)}});
}

LinkChecker.prototype.processCheckCommentLinkResponse = function(details)
{
  var responseText = details.responseText;
  var error = checkError(responseText);
  if (error)
  {
    var linkSpan = document.createElement('span');
    linkSpan.innerHTML = "Wystawiono<br>";
    this.commentLink.parentNode.insertBefore(linkSpan, this.commentLink);
    this.commentLink.style.display = "none";
  }
  this.unmark(this.commentLinkTD);
}

/////////////////////////////////////////////////////////////////
// Coment filtering/coloring related functions
/////////////////////////////////////////////////////////////////
function changeCommentRowBackgroundColor(element, color, doColoring)
{
  var newColor = doColoring ? color : "";
  var childNodes = getChildNodes(element);
  for(var i=0; i<childNodes.length; i++)
  {
    childNodes[i].style.backgroundColor = newColor;
  }

  // Comments on add feedback page consist of one row only.
  // On other pages each comment has 2 rows - so wee need to color it as well.
  if (isAddFeedbackPage == false)
  {
    getFirstChild(getNextSibling(element, 1)).style.backgroundColor = newColor;
  }
}

function hideComment(row, hide)
{
  if (row)
  {
    var displayValue = hide ? "none" : "";
    row.style.display = displayValue;
    // Comments on add feedback page consist of one row only.
    // On other pages each comment has 2 rows - so wee need to hide/show it as well.
    if (isAddFeedbackPage == false)
    {
      getNextSibling(row, 1).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.parentNode.insertBefore(filterCommentTypeMenu, COMMENT_TABLE);
    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("Sprawdz 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.parentNode.insertBefore(filterBuyerSellerMenu, COMMENT_TABLE);
  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.className;
    if((classAttr) && (classAttr == "list-head"))
    {
      COMMENT_TABLE = node;
      commentRows = COMMENT_TABLE.rows;
      break;
    }
  }
  
  // Now group seller and buyer comments also mark positive/neutral/negative comments
  if (commentRows)
  {
    var row;
    // Skip first row - table header
    for(var i=1; i < commentRows.length; i++)
    {
      row = commentRows[i];
      if(row && (getChildNodes(row).length > 1)) // check length to skip comment text rows
      {
        var cell, commentTypeCell;
        var id = "";

        // Mark buyer seller
        if(isAddFeedbackPage)
        {
          cell = select(row, 2);
        }
        else
        {
          cell = getFirstChild(row);
        }
        if(cell)
        {
          var string = getInnerText(cell);
          // TODO correct matching strings
          if(string.match(SELLER_STRING))
          {
            id = id.concat(SELLER_STRING);
          }  
          else if(string.match(BUYER_STRING))
          {
            id = id.concat(BUYER_STRING);
          }
        }

        if (showCommentTypeFilter)
        {
          commentTypeCell = select(row, 1, 0);
          if(commentTypeCell)
          {
            var commentTypeString = getInnerText(commentTypeCell);
            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);
            }
          }
        }

        if (id != "")
        {
          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;
  }

  if(document.location.href.match(/page=feedbacks/) && document.location.href.match(/type=fb_add/))
  {
    isAddFeedbackPage = true;
  }

  findComments();
  if (COMMENT_TABLE)
  {
    filterComments();
    addMenu();
    autocheckLinks();
  }
}

/////////////////////////////////////////////////////////////////
// Start Allegro Tools Comments script
/////////////////////////////////////////////////////////////////

allegrotoolsComments()
