// ==UserScript==
// @name           AllegroTools for IE i FF
// @namespace      http://allegrotoolsie.hopto.org/
// @description    Kilka narzedzi pomocnych w przegladaniu Allegro // v0.20070415.1
// @include        http*://*allegro.pl/*
// @exclude        http*://*allegro.pl/show_user.php?*
// ==/UserScript==

var GET_DESCRIPTIONS_BTN = "_get_descriptions_btn_";
var AUTO_GET_DESCRIPTIONS_CHBX = "_auto_get_descriptions_chbx_";
var NO_KUP_TERAZ_CHBX = "_no_kup_teraz_chbx_";
var ODBIOR_OSOBISTY_ONLY_CHBX = "_odbior_osobisty_only_chbx_";
var CENA_MINIMALNA_CHBX = "_cena_minimalna_chbx_";
var KUP_TERAZ_STRING = "Kup Teraz!";
var KUP_TERAZ_TAG = "_kt_";
var NO_ODBIOR_OSOBISTY_TAG = "_noo_";
var CENA_MINIMALNA_TAG = "_cm_";
var auctions    =  new Array();

// Used to mark whether listing are shown in text-only mode or not
var textOnlyMode = false;

// ----------- icons
var ICON_PROGRES ="data:application/x-shockwave-flash;base64,"+
     "Q1dTCMwBAAB4nAtgWMDAxcAgxMjgIsgABM5M////t2cOAzI7FBhYGEoyMosZ8vNc80pSi9yKEnNT"+
     "GbIZ4ovySxJLMvPzGKYxMXAwyIBIxtmsIO1yYCEmmWksDBzMIBrIY/abxsrALgKUdff3Z9jPEAxk"+
     "MTIkMNg1ABEjA9A+ZkaGmWfOMDKcARHv3r0TMu0NuVrXnak6k4FLzYDp1rYX29YuYEte/H/Gpey8"+
     "llm30h24JA8wqnmu8AwKYJ27+H967pYZDP85BYAGMwGNbmNjYwRSDA5A/n/Oo0CSGcjtAYkyMWyd"+
     "ueas+ly96Wx8zFCe4m6LF0A1LAx3zX0vMAAlWKESypY7IBK79U5vAEmwQyXUYs9BJGaqeU4ASXDC"+
     "JPbGQSQ6lDgaQBLcUAmVWqjEO+u+ByAJXqiE7OcHEIkzxjwHQBL8MKP22EEkVml1LQB7ZT8bP5BU"+
     "YwT65mibxGEeVYcF2WAJAAUyff8=";


var ICON_INFO =  "data:image/gif;base64,"+
     "R0lGODlhEAAQAIMAAAAAAAAAcwYchxA4mg9QuAB79wiG/xtavjV0zCSY/1mm9Ya88qnT+9Tf7vf8"+
     "//8A/yH5BAMAAA8ALAAAAAAQABAAAAR68Ml36iEjz2kV+4yCCdyBNI3joCgikBTCoKqjsC51LCC6"+
     "eKCBwLQoGo8/ROCgaHpqCEXCYCgsE86ng0DtDhNg8ELF7RoEhIJ57BiYrYOCXM6OzwmBQZnKULm9"+
     "AQ8DB2IsDYQJeBIZiGFheIESLwNRTi4BkRsvAZuYGxEAOw==";

var ICON_CLOSE = "data:image/gif;base64,"+
     "R0lGODlhEAAQAIMAAAAAAFJSUo1KTcExOdMuNs81OdZNUvs+Q+1dX/N4e+6Vl/G1tfrPz//v7///"+
     "//8A/yH5BAMAAA8ALAAAAAAQABAAAASG8ElZSLlj6mcJMYhXZNplLE3aLMg4WQiDqmtSCNInr0yP"+
     "soPAgKBAOVaLhcPBUBAEFYW0cVQ6FocDYVAwSKdLhwKRPXANiTQisWSUs1xCmc1klrfDLD1xYNi1"+
     "OF0xYgiFfgoGQQ9caQppj443ARJcCF9fLQKTEwJnaQYjmhsPAZ0Dp5qbDxEAOw==";
     
var ICON_MAIL =  "data:image/gif;base64,"+
     "R0lGODlhDQAJAIMAADEtQmdjhHNzkoWGp5SUtaSiw7Kyz8C92MbG1svL5NfX7d7e9+fn8+/v+/r3"+
     "+/8A/yH5BAMAAA8ALAAAAAANAAkAAARG8JFJh7XPGMZa6x4nGAeDNA63HIQRGIiTGEmaDEXyHo5z"+
     "0AZcQhE4xIyKQqu1eCESh49imiAcAoJE4rOYTn+BhyBALpsfEQA7";
     
var ICON_MAILRE = "data:image/gif;base64,"+
     "R0lGODlhDgAKAIMAAAAAABhSMV5keAiBBQuaCz63PnmSlpGOsqWlxbHPwMfH4Nja8eby7fXz+///"+
     "//8A/yH5BAEAAA8ALAAAAAAOAAoAAARI8L1Dq7lXIsRY603ILMKjKIwijsqBlMUQF2rqKsLMzApy"+
     "kzKHMOYrAhMJBnKwaLZwBELBUYg2na+ANFENCL5gSWBAGAQkaHQEADs=";
     
var ICON_MAIL2 =  "data:image/gif;base64,"+
     "R0lGODlhCgAKAIMAAAAAABsbYDk5eEpKg1hYkm1tonx8ro6OuqamzMDA287O3tLS59ra6+Tk8ff3"+
     "/P8A/yH5BAEAAA8ALAAAAAAKAAoAAARB8ElTzClkGoMYO8NzHEnjOEtCDN15JowhHA2jKEyyIIKR"+
     "vAdEAkEoHE6LhSJREDwKJSVIEHgQDAoiVfIYFAdObgQAOw==";

var ICON_MAIL2RE = "data:image/gif;base64,"+
     "R0lGODlhCgAKAIMAAAAAAB8fb0FDewtpEzSsNFpanGiMiIeHs5iYwZnMorGx0srQ2tbW5+De7fP3"+
     "9/8A/yH5BAMAAA8ALAAAAAAKAAoAAAQ+8MlXzilF2oNWQxlyKIzjNEshHJ7pLMwhKB7jkYowGAmM"+
     "0IrCgJAg2hQyYsNgYIACgWHRoApIBsOBQGCVRAAAOw==";

var ICON_ABOUT =  "data:image/gif;base64,"+
     "R0lGODlhDwAKAIMAAAAAAP////////8A/wAAgIAAgACAgMDAwICAgP8AAAD/AP//AAAA//8A/wD/"+
     "/////yH5BAMAAAMALAAAAAAPAAoAAAQdcMg5gKV4gprz3h1lgWFpctqnktX1ce8YwzQ9rxEAOw==";

var ICON_SS =  "data:image/gif;base64,"+
     "R0lGODlhCgAKAIMAADQTCF4rE4AuBYVgTqNBDp9xX5+Deb9FCNRNCMdgKcZ6VMyQc9Kum+HIuezg"+
     "3v8A/yH5BAEAAA8ALAAAAAAKAAoAAARF8DVTjBmsPWdCYYMgGFwwOAWhEkoBFA6THAcbBILSNEuC"+
     "EDgBIbFwLBCJAY6AQPAQCsbykJAhMgbRYaE46CSFsCHKeEQAADs=";
     
// ----------- stars
var STAR1 =  "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAAL2ECMaEAM6MANqQAM6QENSeOe+fAPqpC/m1K/fDV/nOff3ch/vhq/jt"+
     "z/8A/yH5BAMAAA8ALAAAAAALAAoAAAQ38Em53LzPqYXnStXkME3zJUxKngmCHEfSZIr7DgZzKQcx"+
     "BBxRYlAQFBS7hKGhKOQkjsVi9thwIgA7";

var STAR5 =  "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAAMYAAMYICM4AANoAAM4YGM5FRfUCAvoaGvpAQPBubveCgvSbm/i1tfjW"+
     "1v8A/yH5BAEAAA8ALAAAAAALAAoAAAQ58Em53LzPqYXnSoolOUzTKEnCrOWHvMdBJE2WIPEhKMyl"+
     "yARBb+JIDAqCAmeiQBgai8JztKo9NpwIADs=";
     
var STAR25 =  "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAAAAAxggIxgAA1gwM1iEhxmBg0gEB8x0d+z8/925u84KC95ub9LW1+Nvb"+
     "/f8A/yH5BAEAAA8ALAAAAAALAAoAAAQ48Em53LzPqYXnSoolOUzTKEnCrOWHvEecNJmCxAdhMJdy"+
     "DAMBb+JIDAqCAmdiMzQWhQItsxJtOBEAOw==";
     
var STAR125 =  "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAAL1aEL9kKNZhEfJhBN6LWOW8oP9jAPxtCvx1Hv+MPv+iYP2xeP3UuPzj"+
     "1/8A/yH5BAEAAA8ALAAAAAALAAoAAARD8LnmzKKtPbnY+gpjbGBiJsjWLAqKHEjCrIryHgcxFBqT"+
     "4DmCwPFotAjIQSBgcCwKhcRAWRAUiA/DwMrceLOGRtgbAQA7";
     
var STAR625 =  "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAAIwQvY4jvaIA4a0A87UE+6gx270V/MQs/85P/NBl+8157dmi8eq59/La"+
     "/f8A/yH5BAEAAA8ALAAAAAALAAoAAAQ+8LnmmKL0ScWTX43WIQdCao2SHEV7HKBiti0xgI9M20bY"+
     "rITgIBBgOFQKw8AQMAgWDg2juRAwNNjHAsQIaSIAOw==";

var STAR3125 = "data:image/gif;base64,"+
     "R0lGODlhCwAKAIMAAAAAADkQvU4owT8T2TwG8HNS3qmW6TkA/0IM/1Ig/3FF/4he/6CE/cm7/ePc"+
     "/v8A/yH5BAEAAA8ALAAAAAALAAoAAARA8LnmzKKtvdeWV4vCaM+XnAmydUp6HEgyhgryHsRQaExy"+
     "EwSBptECAgMBgyO0EAwGgYKg4FgNpsmN9mEwNLzaCAA7";
// -------------- backgorunds
var BG_BYSTR = "data:image/png;base64,"+
     "iVBORw0KGgoAAAANSUhEUgAAAAQAAAAECAIAAAFRlDm/AAAAB3RJTUUH1gwHDRgVt4pvywAAAAlw"+
     "SFlzAAAPYQAAD2EBqD+naQAAAARnQU1BAACxjwv8YQUAAAAYSURBVHjaY/j/nwEGoEwQBWEyoovD"+
     "FQMAkc0N9HFYUnUAAAAASUVORK5CYII=";
     
var POPUP =
     " <div id='popupHeader'>"+
     "  <div id='iconClose' style='margin:5px; float: left; cursor: pointer;' onclick='var p = document.getElementById(\"AllegroToolsPopup\"); p.parentNode.removeChild(p);'>"+
     "    <img border='0' src='"+ICON_CLOSE+"' />"+
     "  </div>"+
     "  <div id='iconInfo' style='margin:5px; float: left'>"+
     "   <img border='0' src='"+ICON_INFO+"' />"+
     "  </div>"+
     "  <div id='popupTitle' style='margin: 5px; float: left'>"+
     "   :TITLE:"+
     "  </div>"+
     " </div>"+
     " <div id='popupContent' style='clear: both;margin: 10'>"+
     "  :MESSAGE:"+
     " </div>";


/////////////////////////////////////////////////////////////////
//// 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);
  }
} 

// FF passes event to the handler function, while IE does not
// Call this function fit the ergument of the handler function:
// If e is not null (FF) then it will be returned. Otherwise (IE)
// the event will be retrieved from the window object and this value
// will be returned instead.
function getEvent(source)
{
  if (source)
  {
    return source;
  }
  else
  {
    return window.event;
  }
}

// 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;
}

// 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;
}

/////////////////////////////////////////////////////////////////


/**
 * wycina htmlz info o userze
 */
function getSeller(str){
  if(str.match(/(<b><span class="uname".*?<\/b>)/g))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

/**
 * wycina numer aukcji z linka aukcji
 */
function getAuctionNumberFromLink(str){
  if(str.match(/item(\d*)_/g))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}
/**
 * pobiera date konca aukcji
 */
function getEndTime(str){
  if(str.match(/(<span class="small">\(.{3} \d{2} .{3} \d{4} \d{2}:\d{2}:\d{2} .+?\)<\/span>)/g))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}

/**
 * pobiera lokalizacje aukcji
 */
function getLocation(str){
  if(str.match(/<tr>\s*?<td.*?>Lokalizacja<\/td>\s*?<td.*?>(.*?)<\/td>\s*?<\/tr>/))
  {
    return RegExp.$1;
  }
  else
  {
    return null;
  }
}
function checkOsobisty(str)
{
  if(str.match(/<div class="li4">Odbi.r osobisty<\/div>/))
  {
    return true;
  }
  else
  {
    return false;
  }
}

function checkCenaMinimalna(str)
{
  if(str.match(/<span class="small">Cena <a href=javascript:OpenHelp\(46\)>minimalna<\/a> nie zosta.a osi.gni.ta\.<\/span>/))
  {
    return true;
  }
  else
  {
    return false;
  }
}


/**
 * zamienia string allegrowej daty w date JS
 */
function makeDate(str){
  var PATTERN = new Array('sty','lut','mar','kwi','maj','cze','lip','sie','wrz','paz','lis','gru','CET');
  var REPLACE = new Array('jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec', -1);
  var data = str.match(/\d{2} .{3} \d{4} \d{2}:\d{2}:\d{2} /g)[0];

  data = data.replace(PATTERN, REPLACE);

  return Date.parse(data);
}
/**
 * String.prototype
 * replace na arrayach
 */
String.prototype._replace = String.prototype.replace;
String.prototype.replace = function(pattern, replace){
  if(typeof pattern == "string" || typeof pattern == "function"){
    return this._replace(pattern, replace);
  }else{
    if(typeof replace == "string"){
      var ret = this.toString();
      for (var i=0; i<pattern.length; i++){
        ret = ret._replace(pattern[i], replace);
      }
      return ret;
    }else{
      var ret = this;
      for (var i=0; i<pattern.length; i++){
        var m = Math.min(i, replace.length);
        ret = ret._replace(pattern[i], replace[m]);
      }
      return ret;    
    }
  }
}

/**
 * Date.prototype
 * liczy czas od tej daty (this) do danej innej, wyjscie formatuje
 */
Date.prototype.timeTo = function(otherdate){
  var delta = otherdate-this;
  
  return new TimeTo(delta);
}
/**
 *
 */
function TimeTo(miliseconds){
  this.miliseconds = miliseconds;
  this.ms = miliseconds % 1000;
  this.s = Math.floor(miliseconds/1000) % 60;
  this.m = Math.floor(miliseconds/1000/60) % 60;
  this.h = Math.floor(miliseconds/1000/60/60) % 24;
  this.d = Math.floor(miliseconds/1000/60/60/24);

}
TimeTo.prototype.toString = function(format){
  if(!format || format == "auto"){
    if(Math.abs(this.d)>0){
      format = ":dd :hh :mm";
    }else if(Math.abs(this.h)>0){
      format = ":hh :mm :ss";
    }else if(Math.abs(this.m)>0){
      format = ":mm :ss";
    }else{
      format = ":ss";
    }
  }
  if (this.miliseconds>0){
    return  format.replace(  [/:d/g,  /:M/g,  /:h/g,  /:m/g,  /:s/g], 
                [this.d,this.M,  this.h,  this.m,  this.s]);
  }else{
    return  format.replace(  [/:d/g,  /:M/g,  /:h/g,  /:m/g,  /:s/g], 
                [-this.d,-this.M,  -this.h,  -this.m,  -this.s]);
  
  }

}
/**
 *
 */
Array.prototype.indexOf = function(value){
  for(v in this){
    if(value == this[v])
      return v;
  }
  return -1;
}
/**
 *  klasa User
 */
function User(){
  this.uid    = "";
  this.nick   = "";
  this.points = "";
  this.stars  = [];
  this.about  = "";
  this.ss     = "";
  this.itemId = "";
  this.blacklisted = false;
  this.location = "";
  this.osobisty = "";
};
User.prototype.fromHTML = function(str){
  str.match(/uid=([\d]+).*?([\w-]+).*?\((\-?[\d]+)\)/);
// -- podstawowe
  this.uid = RegExp.$1;
  this.nick = RegExp.$2;
  this.points = RegExp.$3;
  this.stars = str.match(/star\d+/g);
  this.about = (str.match(/omnie/))?true:false;
  this.ss = (str.match(/supers/))?true:false;
  var bl = GM_getValue("AT_blacklist", "");
  this.blacklisted = (bl && bl.match(":" + this.uid + ":")) ? true : false;
// -- inne  
}

User.prototype.userURL = function(){
  return (this._userURL)?(this._userURL):(this._userURL = ('/show_user.php?uid=:UID:')._replace(/:UID:/g, this.uid));
}
User.prototype.aboutURL = function(){
  return (this.aboutURL)?(this.aboutURL):(this.aboutURL = ('/my_page.php?uid=:UID:')._replace(/:UID:/g, this.uid));
}

User.prototype.toHTML = function(){

  var aboutHTML       =  "<a href='/my_page.php?uid=:UID:'><img src=':ICON_ABOUT:' title='Strona o mnie'/></a>";
  var starHTML        =  "<img src=':SRC:' title='*'/>";
  var mailHTML        =  "<a href='/email_to_user.php?uid=:UID:'><img src=':ICON_MAIL:' title='Mail do sprzedajacego'></a>";
  var mailAuctionHTML =  "<a href='/email_to_user.php?uid=:UID:&item_id=:IID:'><img src=':ICON_MAILRE:' title='Mail do sprzedajacego w zwiazku z ta aukcja'></a>";
  var ssHTML          =  "<img src=':ICON_SS:' title='Super Sprzedawca'/>";
  var mainStr         =  "<span id='user:UID::IID:' style='font-size:8pt; color: #afafaf;'><a href='/show_user.php?uid=:UID:' style='font-size:8pt; color: #afafaf;'>:NICK:</a> <span name='p'>(:POINTS:)</span> :MAILTO: :STARS: :ABOUT: :SS: :MAILAUCTION: :LOCATION::OSOBISTY:</span> :BLACKLIST:";

  
  var stars = "";
  if(this.stars){
    for (var i = 0; i<this.stars.length; i++){
      var s;
      switch(this.stars[i])
      {
        case "star1":s=STAR1;break;
        case "star5":s=STAR5;break;
        case "star25":s=STAR25;break;
        case "star125":s=STAR125;break;
        case "star625":s=STAR625;break;
        case "star3125":s=STAR3125;break;
      }
      stars += starHTML.replace(':SRC:', s);
    }
  }
  var about = "";
  if(this.about){
    about = aboutHTML.replace([/:UID:/g, /:ICON_ABOUT:/g], [this.uid, ICON_ABOUT]);
  }
  
  var ss = "";
  if(this.ss){
    ss = ssHTML._replace(/:ICON_SS:/g, ICON_SS);
  }
  
  
  var mailAuction = "";
  if (this.itemId){
    mailAuction = mailAuctionHTML.replace([/:UID:/g, /:IID:/g, /:ICON_MAILRE:/], [this.uid, this.itemId, ICON_MAILRE]);
  }
  
  var mailto = mailHTML.replace([/:UID:/g, /:ICON_MAIL:/g],[this.uid, ICON_MAIL]);
  
  var bl = (this.blacklisted == true) ? "<span style='font-size:8pt; color: #FFFFFF; background-color: #000000' ><b>&nbsp;CZARNA LISTA&nbsp;</b></span>" : "";

  var osobisty = (this.osobisty == true) ? "<span title='Odbior Osobisty'> <b>[OO]</b></span>" : "";

  var p = [/:UID:/ig,  /:NICK:/ig,  /:POINTS:/ig,  /:STARS:/ig,  /:ABOUT:/ig,  /:SS:/ig,  /:MAILTO:/ig,  /:MAILAUCTION:/ig,  /:BLACKLIST:/ig,
           /:IID:/ig,  /:LOCATION:/ig, /:OSOBISTY:/ig];
  var r = [this.uid,  this.nick,   this.points,  stars,        about,        ss,        mailto,        mailAuction,        bl,
           this.itemId, this.location, osobisty];

  mainStr = mainStr.replace(p,r);

  return mainStr;
}

User.prototype.setLocation = function(location){
  if (location != null)
  {
    this.location = location;
  }
}

User.prototype.setOsobisty = function(osobisty){
  this.osobisty = osobisty;
}

/**
 * klasa Processor
 */
function Processor(node){
  this.node = node;
  this.mark();
  this.process();
}

Processor.processedUsers = new Array();

Processor.prototype.mark = function(){
  
  if(!this.fotoTD){
    if(textOnlyMode)
    {
      this.fotoTD = document.createElement("TD");
      this.fotoTD.width = 5;
      var tr = select(this.node, 0, 0, 0, 0);
      tr.insertBefore(this.fotoTD, getFirstChild(tr));
    }
    else
    {
      this.fotoTD = select(this.node, 0, 0, 0, 0, 0);
    }
  }
  this.fotoTD.style.backgroundImage = "url('"+BG_BYSTR+"')";
}
Processor.prototype.unmark = function(){
  this.fotoTD.style.backgroundImage = "";
}

Processor.prototype.process = function(){
  this.auctionURL = select(this.node, 0, 0, 0, 0, 1, 0, 0).href;
  var me = this;
  try
  {
    GM_xmlhttpRequest({method:"GET", url:this.auctionURL, onload:function(d){me.processAuction(d)}, onerror:function(d){me.processError(d)}});
  }
  catch(e)
  {
    me.processError();
  }

}

Processor.prototype.processError = function(details){
    this.unmark();
}

Processor.prototype.processAuction = function(details){
  var td = select(this.node, 0, 0, 0, 0, 1);
  td.myVar = "moja wartosc";
  var userHTML = getSeller(details.responseText);
  if (userHTML)
  {
    var u = new User();
    u.itemId = getAuctionNumberFromLink(this.auctionURL);
    u.fromHTML(userHTML);
    u.setLocation(getLocation(details.responseText));
    var odbiorOsobisty = checkOsobisty(details.responseText);
    if(odbiorOsobisty)
    {
      u.setOsobisty(odbiorOsobisty);
    }
    else
    {
      this.node.id = NO_ODBIOR_OSOBISTY_TAG.concat(this.node.id);
      if (GM_getValue("AT_odbior_osobisty_only", false))
      {
        this.node.style.display = "none";
      }
    }

    var cenaMinimalna = checkCenaMinimalna(details.responseText);
    if(cenaMinimalna && (document.location.href.match(/buy=1/) == null))
    {
      this.node.id = CENA_MINIMALNA_TAG.concat(this.node.id);
      var priceP = select(this.node, 1, 0);
      if(priceP)
      {
        priceP.innerHTML = "<span title='Cena minimalna nie zostala osiagnieta' style='font-size:8pt; color: #afafaf;'><b>[&lt;CM]</b></span>&nbsp;".concat(priceP.innerHTML);
      }

      if (GM_getValue("AT_cena_minimalna", false))
      {
        this.node.style.display = "none";
      }
    }

    var p = td.appendChild(document.createElement('p'));
    p.innerHTML = u.toHTML();
  
    var endTime = makeDate(getEndTime(details.responseText));
    var timeTD;
    if(document.location.href.match(/buy=1/)){
      timeTD = select(this.node, 2);
    }else{
      timeTD = select(this.node, 3);
    }
    timeTD.removeChild(select(timeTD, 0));
    var now = new Date();
    var t = now.timeTo(endTime);
    var timeDIV = document.createElement('div');
    if(t.miliseconds<10*60*1000 && t.miliseconds>0){
      timeDIV.style.color = "#ff0000";
    }
    timeDIV.style.textAlign = "center";
    timeDIV.appendChild(document.createTextNode(t.toString()));
    timeTD.appendChild(timeDIV);
    var uURL = "http://" + document.domain + u.userURL();
    var me = this;
    GM_xmlhttpRequest({method:"GET", url:uURL, onload:function(d){me.processUserPage(d,u)}, onerror:function(d){me.processError(d)}});
  }
  else
  {
    this.processError();
  }
}
Processor.prototype.processUserPage = function(details, user){
    Processor.processedUsers.push(user.uid);
    var table = details.responseText._replace(/[\s]+/g, " ").match(/<table[^>]*?table-info.*?<\/table>/)[0];
    this.userDetails = document.createElement('div');
    this.userDetails.style.position = 'absolute';
    this.userDetails.style.left = '0px';
    this.userDetails.style.top = '0px';
    this.userDetails.style.display = 'none';
    this.userDetails.innerHTML = table;
    select(this.node, 0, 0, 0, 0, 1, 1, 0, 1).appendChild(this.userDetails);
    this.sp = select(this.node, 0, 0, 0, 0, 1, 1, 0, 1);
    var me = this;
    registerEventHandler(this.sp, 'mouseover', function(e){me.showUserDetails(e)});
    registerEventHandler(this.sp, 'mouseout', function(e){me.hideUserDetails(e)});

    this.unmark();    
}
Processor.prototype.showUserDetails = function(e){
  var event = getEvent(e);
  this.userDetails.style.left = event.clientX + document.body.scrollLeft + 5;
  this.userDetails.style.top = event.clientY + document.body.scrollTop + 5;
  this.userDetails.style.display = '';
}
Processor.prototype.hideUserDetails = function(d){
  this.userDetails.style.display = 'none';
}

// 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;
}

function processAuctionTable(table, auctions)
{
  if (table)
  {
    var rows = table.rows;
    // Skip non-auction rows (ones without title field)
    for(var i = 0; i<rows.length;i++)
    {
      if (select(rows[i], 0, 0, 0, 0, (textOnlyMode ? 0 : 1), 0, 0) != null)
      {
        auctions.push(rows[i]);
      }
      var priceElement = select(rows[i], 1, 0);
      if (priceElement)
      {
        var priceElementText = getInnerText(priceElement);
        if (priceElementText && priceElementText.match(KUP_TERAZ_STRING))
        {
          rows[i].id = KUP_TERAZ_TAG.concat(rows[i].id);
        }
      }
    }
  }
}

function storeBlacklistTable()
{
  var forms = document.getElementsByTagName("form");
  var blacklist = null;
  var blacklistStr = ":";

  if (forms)
  {
    for(var i = 0; i < forms.length; i++)
    {
      if (forms[i].action.match(/my_settings_change.php\?type=set_buyer&option=black_rmv/))
      {
        blacklist = getChildNodes(select(forms[i], 0, 0));
        break;
      }
    }
  }
  
  if (blacklist)
  {
    for(var i = 0; i < blacklist.length; i++)
    {
      if (blacklist[i] && getChildNodes(blacklist[i]) && (getChildNodes(blacklist[i]).length == 3))
      {
        userLink = select(blacklist[i], 1, 0, 0).href;
        if (userLink)
        {
          if (userLink.match(/uid=([\d]+)/))
          {
            blacklistStr = blacklistStr.concat(RegExp.$1 + ":");
          }
        }
      }
    }
  }
  
  GM_setValue("AT_blacklist", blacklistStr);
}

function handleAutoGetDescriptionsCheckbox()
{
  var autoGetDescriptionsValue = getCheckbox(AUTO_GET_DESCRIPTIONS_CHBX);
  GM_setValue("AT_auto_get_descriptions", autoGetDescriptionsValue);
  showButton(GET_DESCRIPTIONS_BTN, !autoGetDescriptionsValue);
  autoGetDescriptions();
}

function handleGetDescriptionsButton()
{
  enableButton(GET_DESCRIPTIONS_BTN, false);
  getDescriptions();
}

function handleNoKupTerazCheckbox()
{
  var noKupTeraz = getCheckbox(NO_KUP_TERAZ_CHBX);
  GM_setValue("AT_no_kup_teraz", noKupTeraz);
  filterAuctions();
}

function handleOdbiorOsobistyOnlyCheckbox()
{
  var odbiorOsobistyOnly = getCheckbox(ODBIOR_OSOBISTY_ONLY_CHBX);
  GM_setValue("AT_odbior_osobisty_only", odbiorOsobistyOnly);
  filterAuctions();
}

function handleCenaMinimalnaCheckbox()
{
  var cenaMinimalna = getCheckbox(CENA_MINIMALNA_CHBX);
  GM_setValue("AT_cena_minimalna", cenaMinimalna);
  filterAuctions();
}

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)
{
  return "<input style=\"font-size=8pt\" title=\"" + help + "\" type=\"button\" id=\"" + id + "\" value=\"" + title +"\"/>";
}

function getCheckboxHtml(title, help, id)
{
  return "<input style=\"font-size=8pt\" title=\"" + help + "\" type=\"checkbox\" id=\"" + id + "\"/><label style=\"font-size=8pt\" title=\"" + help + "\" for=\"" + id + "\">" + title + "</label>";
}

function addTableRow(tableRow, innerHTML, header)
{
  var tr = document.createElement('tr');
  var td = document.createElement('td');
  if(header)
  {
    td.style.backgroundColor="#366382"
    td.style.color="#FFFFFF"
    td.style.borderTopStyle="solid";
    td.style.borderTopColor="#002449";
    td.style.borderTopWidth="1px";
    td.style.borderBottomStyle="solid";
    td.style.borderBottomColor="#002449";
    td.style.borderBottomWidth="1px";
  }
  else
  {
    td.style.backgroundColor="#E7DAD1";
  }
  if(innerHTML)
  {
    td.innerHTML = innerHTML;
  }
  tr.appendChild(td);
  tableRow.parentNode.insertBefore(tr, tableRow);
}

function addAllegrotoolsOptionsMenu()
{
  // First find Allegro Options menu
  var tdNodes = document.getElementsByTagName("td");
  if(tdNodes)
  {
    for(var i = 0; i < tdNodes.length; i++)
    {
      if((tdNodes[i].className == "list-menu-descx") && (getInnerText(tdNodes[i]).match(/Opcje ?/)))
      {
        var row = tdNodes[i].parentNode;
        addTableRow(row, "<b>Opcje AllegroTools</b>", true);
        addTableRow(row, "<table  cellspacing='0' cellpadding='0' border='0'><tr>" +
                         "<td><span class='small'>" + getCheckboxHtml("Autoopisy", "Automatyczne pobieranie opisow uzytkownikow", AUTO_GET_DESCRIPTIONS_CHBX ) + "</span></td>" +
                         "<td>&nbsp;</td>" +
                         "<td><span class='small'>" + getButtonHtml("Pobierz", "Pobiera opisy uzytkownikow", GET_DESCRIPTIONS_BTN) + "</span></td>" +
                         "</tr></table>");
        addTableRow(row, "<span class='small'>" +
                         getCheckboxHtml("Ukryj <font color='#e46632'>Kup Teraz!</font>", "Pomija aukcje Kup Teraz!", NO_KUP_TERAZ_CHBX) +
                         "</span>");
        addTableRow(row, "<span class='small'>" +
                         getCheckboxHtml("Tylko z odbiorem osobistym", "Wyswietla tylko aukcje z zanznaczona opcja odbioru osobistego", ODBIOR_OSOBISTY_ONLY_CHBX) +
                         "</span>");
        addTableRow(row, "<span class='small'>" +
                         getCheckboxHtml("Ukryj <b>[&lt;CM]</b>", "Ukrywa aukcje, w ktorych cena minimalna nie zostala osiagnieta", CENA_MINIMALNA_CHBX) +
                         "</span>");

        var autoGetDescriptions  = GM_getValue("AT_auto_get_descriptions", true);
        GM_setValue("AT_no_kup_teraz", false); // overwrite the AT_no_kup_teraz setting so it is not remenbered across sessions
        var noKupTeraz = GM_getValue("AT_no_kup_teraz", false);
        GM_setValue("AT_odbior_osobisty_only", false); // overwrite the AT_odbior_osobisty_only setting so it is not remenbered across sessions
        var odbiorOsobistyOnly = GM_getValue("AT_odbior_osobisty_only", false);
        GM_setValue("AT_cena_minimalna", false); // overwrite the AT_cena_minimalna setting so it is not remenbered across sessions
        var cenaMinimalna = GM_getValue("AT_cena_minimalna", false);

        setCheckbox(AUTO_GET_DESCRIPTIONS_CHBX, autoGetDescriptions);
        enableButton(GET_DESCRIPTIONS_BTN, true);
        showButton(GET_DESCRIPTIONS_BTN, !autoGetDescriptions);
        setCheckbox(NO_KUP_TERAZ_CHBX, noKupTeraz);
        setCheckbox(ODBIOR_OSOBISTY_ONLY_CHBX, odbiorOsobistyOnly);
        setCheckbox(CENA_MINIMALNA_CHBX, cenaMinimalna);
        registerEventHandler(document.getElementById(AUTO_GET_DESCRIPTIONS_CHBX), "click", handleAutoGetDescriptionsCheckbox);
        registerEventHandler(document.getElementById(GET_DESCRIPTIONS_BTN), "click", handleGetDescriptionsButton);
        registerEventHandler(document.getElementById(NO_KUP_TERAZ_CHBX), "click", handleNoKupTerazCheckbox);
        registerEventHandler(document.getElementById(ODBIOR_OSOBISTY_ONLY_CHBX), "click", handleOdbiorOsobistyOnlyCheckbox);
        registerEventHandler(document.getElementById(CENA_MINIMALNA_CHBX), "click", handleCenaMinimalnaCheckbox);
        break;
      }
    }
  }
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function filterAuctions()
{
  var hideKupTeraz = GM_getValue("AT_no_kup_teraz", false);
  var odbiorOsobistyOnly = GM_getValue("AT_odbior_osobisty_only", false);
  var cenaMinimalna = GM_getValue("AT_cena_minimalna", false);
  for(var i=0; i<auctions.length;i++)
  {
    element = auctions[i];
    if(element)
    {
      if(((element.id.match(KUP_TERAZ_TAG) && hideKupTeraz)) ||
          ((element.id.match(NO_ODBIOR_OSOBISTY_TAG)) && odbiorOsobistyOnly) ||
          ((element.id.match(CENA_MINIMALNA_TAG)) && cenaMinimalna))
      {
        element.style.display = "none";
      } 
      else
      {
        element.style.display = "";
      }
    }
  }

}

function getDescriptions()
{
  // Process auction nodes
  for(var i=0; i<auctions.length;i++)
  {
    var p = new Processor(auctions[i]);
  }
}

function autoGetDescriptions()
{
  if(isEnabledButton(GET_DESCRIPTIONS_BTN) && getCheckbox(AUTO_GET_DESCRIPTIONS_CHBX))
  {
    handleGetDescriptionsButton();
  }
}

function addReportItemLink()
{
  if(document.location.href.match(/item(\d+).*?.html/))
  {
    var auctionNumber = RegExp.$1;
    var divs = document.getElementsByTagName("div");
    if(divs)
    {
      var div = false;
      for(var i = 0; i < divs.length; i++)
      {
        div = divs[i];
        if(div.className == "right smaller")
        {
          if(div.innerHTML.match("report_item.php") == null)
          {
            div.innerHTML = div.innerHTML +
                            "<img src='/site_images/1/0/common/bull1.gif' width='9' height='12' alt='' title='' class='tomiddle' />" +
                            "<a href='/report_item.php?item_id=" + auctionNumber + "' class='spec'><span>Zglos naruszenie zasad</span></a>";
          }
          break;
        }
      }
    }
  }
}

function allegrotools()
{
  var node, classAttr;
  var tables = document.getElementsByTagName("table");

  // If on the buyer property page
  if(document.location.href.match(/page=settings/) && document.location.href.match(/type=set_buyer/))
  {
    // Store the blacklist
    storeBlacklistTable();
  }

  // Check Whether we are displaying in text only mode and modifi description index if necessary
  if(document.location.href.match(/st=text/) || document.location.href.match(/view=text/))
  {
    textOnlyMode =  true;
  }

  // First find tables with Auction listings and store all listed auction nodes
  for (var i = 0; i < tables.length; ++i)
  {
    node = tables[i];
    classAttr = node.className;
    if((classAttr) && (classAttr == "listing_f" || classAttr == "listing_r"))
    {
      processAuctionTable(node, auctions);
    }
  }

  // If on the main page
  if(document.location.pathname == "/"){
    var searchInput = document.getElementById('searchstr');
    if (searchInput)
    {
      searchInput.focus();
    }
    var searchForm = searchInput.form;
    div = document.createElement('div');
    div.setAttribute('style','margin-bottom:5px');
    div.innerHTML = 
        '<input type="checkbox" id="description_id" name="description" value="1" />'+
        '<label for="description_id"><span class="small">Szukaj rowniez w opisach</span></label><br/>'+
        '<input type="checkbox" value="1" name="listing" id="listing_id"/>'+
        '<label for="listing_id"><span class="small">Tylko nowe (ostatnie 24h)</span></label><br/>'+
        '<input type="hidden" name="listing_sel" value="1"/>'+
        '<input type="hidden" name="listing_interval" value="7"/>'+
        '<input type="checkbox" value="1" name="buy" id="buy_id"/>'+
        '<label for="buy_id"><span class="small">Tylko <span class="textBN">Kup Teraz!</span></span></label>';
    searchForm.insertBefore(div,searchInput.nextSibling);
  }
  addAllegrotoolsOptionsMenu();
  autoGetDescriptions();
  filterAuctions()
  
  addReportItemLink();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Start Allegro Tools script
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
allegrotools()

