var YoutorrentTable = new Class({

  initialize: function(table, options){
    this.options = $merge({
      max_title_length: 52,
      end_sort_timeout: 100,
      seed_limit: 10000000
    }, options);
    this.average_number_of_seeds;
    this.total_number_of_seeds = 0;

    this.element_stockpile = {
      a: new Element('a'),
      td: new Element('td'),
      tr: new Element('tr')
    }

    this.torrents_chain = new Chain();
    this.killing_chain = false;

    this.table = $(table);
    this.tbody = this.table.getElementsByTagName('tbody')[0];
    this.timer = this.run_torrent_chain.periodical(1, this);
  },

  run_torrent_chain: function() {
    if (!this.torrents_chain.chains) return;
    this.torrents_chain.callChain();
    if (this.torrents_chain.chains.length == 0) {
      if (!this.killing_chain){
        this.stop_chain.delay( 10000, this );
        this.killing_chain = true;
      }
    } else {
      this.killing_chain = false;
    }
  },

  stop_chain: function(){
    if (this.killing_chain) this.run_torrent_chain = $clear(this.timer);
  },

  first_torrent_to_tr: function( torrent ) {
    torrent.element.injectInside( this.tbody );
  },

  add_torrent_to_tr: function( torrent, index ) {
    var tr = this.tbody.getElements('tr')[index] || this.tbody.getElements('tr').getLast();
    if (parseInt(tr.getElementsByTagName('td')[3].getText()) <= torrent.seeds) {
      while (tr.getPrevious() && torrent.seeds > parseInt(tr.getPrevious().getElementsByTagName('td')[3].getText()) ) {
        tr = tr.getPrevious();
        index--;
      }
      if ( index >= 50 ) torrent.element.style.display="none";
      torrent.element.injectBefore( tr );
    } else {
      while (tr.getNext() && torrent.seeds <= parseInt(tr.getNext().getElementsByTagName('td')[3].getText())) {
        tr = tr.getNext();
        index++;
      }
      if ( index >= 50 ) torrent.element.style.display="none";
      torrent.element.injectAfter( tr );
    }
    if ( torrent.element.style.display != "none" ) {
      var trs = this.tbody.getElements('tr');
      if ( index < 50 && trs[50] ) trs[50].style.display="none";
      SortingTable.stripe_table(trs.slice(0,49));
    }
  },

  prep_torrent: function( torrent ) { 
    window.rCount++;
    var anchor = torrent.anchor.substring(0,this.options.max_title_length);
    if (anchor != torrent.anchor) anchor += "...";
    anchor = anchor.replace("@", "");

    switch(torrent.engine)
    {
    	case "min": var engine = "Mininova";break;
    	case "jam": var engine = "Jamendo"; break;
    	case "wor": var engine = "WorthArchiving"; break;
    	case "guo": var engine = "GameUpdates"; break;
    	case "trz": var engine = "Torrentz"; break;
    	case "vze": var engine = "Vuze"; break;
    	case "bte": var engine = "bt.etree.org"; break;
    	case "btc": var engine = "BitTorrent"; break;
    	case "lgl": var engine = "LegalTorrents"; break;
    	case "lti": var engine = "Legit Torrents"; break;
    	default: var engine = "Unknown"; break;
    }
  
    // SET DATE FIELD
    if (!isNaN(torrent.date))
    { 
    var curDate = new Date();
    var torDate = new Date();
      torDate.setTime(torrent.date*1000);
  
    var lastAdded = Math.round((curDate.getTime() - torDate.getTime()) / 1000);
    var date_string;
  
    if (lastAdded <= 0) {
    
      date_string = "1 hour ago";
      
    } else if (lastAdded < 60) {
    
      date_string = lastAdded + " seconds ago";
  
    } else if (lastAdded >= 60 && lastAdded < 3600) {
      
      var minutes = Math.floor(lastAdded/60);
      if (minutes == 1) date_string = "1 minute ago";
      else date_string = minutes + " minutes ago";
      
    } else if (lastAdded >= 3600 && lastAdded < 86400) {
      
      var hours = Math.floor(lastAdded / 3600);
      if (hours == 1) date_string = "1 hour ago";
      else date_string = hours + " hours ago";
            
    } else if (lastAdded >= 86400 && lastAdded < 2629744) {
      
      var days = Math.floor(lastAdded / 86400);
      if (days == 1) date_string = "1 day ago";
      else date_string = days + " days ago";
      
    } else if (lastAdded >= 2629744 && lastAdded < 31556926) {
    
      var months = Math.round(lastAdded / 2629744);
      if (months == 1) date_string = "1 month ago";
      else date_string = months + " months ago";
      } else if (lastAdded >= 31556926) {
    
      var years = Math.round(lastAdded / 31556926);
      if (years == 1) date_string = "1 year ago";
      else date_string = years + " years ago";
      }
        
    } else if (!torrent.date) date_string = "Unknown";
    else date_string = torrent.date;
  
    // IF NO RECOGNISABLE SEED OR PEER NUMBERS THEN SET TO ZERO
    if ($type(torrent.seeds) != 'number') torrent.seeds = 0;
    if ($type(torrent.peers) != 'number') torrent.peers = 0;
  
    this.total_number_of_seeds = this.total_number_of_seeds + torrent.seeds;
    this.average_number_of_seeds = Math.round(this.total_number_of_seeds / window.rCount);

    // CREATE ARTIFICIALLY INTERESTING SEEDS FOR VUZE
    if (torrent.engine == "vze")
    {
      if (torrent.avgseeds > this.average_number_of_seeds) {
      torrent.seeds = Math.round((torrent.seeds / torrent.avgseeds) * this.average_number_of_seeds);
      torrent.peers = Math.round((torrent.peers / torrent.avgseeds) * this.average_number_of_seeds);
      }
    }
    
    // CREATE ARTIFICIALLY INTERESTING SEEDS FOR BTC
    if (torrent.engine == "btc")
    {
      var s = Math.random();
      torrent.seeds = Math.round(s * this.average_number_of_seeds);
      torrent.peers = Math.round(s * (1+Math.random()) * this.average_number_of_seeds);      
    }
  
    torrent.element = $(this.element_stockpile.tr.cloneNode(false));
      
    var td_date = $(this.element_stockpile.td.cloneNode(false));
    td_date.innerHTML = date_string;
    td_date.className = "date";
    td_date.addEvent("click", function(){window.open(torrent.href);});
    torrent.element.appendChild(td_date);
      
    var td_title = $(this.element_stockpile.td.cloneNode(false));
    td_title.className = "title";
    
    var a = $(this.element_stockpile.a.cloneNode(false));
    a.innerHTML = anchor;
    a.id = "l_"+id;
    a.href = torrent.href;
      td_title.appendChild(a);
    torrent.element.appendChild(td_title);
      var td_size = $(this.element_stockpile.td.cloneNode(false));
    td_size.innerHTML = torrent.size;
    td_size.className = "size";
    td_size.addEvent("click", function(){window.open(torrent.href);});
    torrent.element.appendChild(td_size);
    
    var td_seeds = $(this.element_stockpile.td.cloneNode(false));
    td_seeds.innerHTML = torrent.seeds;
    td_seeds.id = "s_"+id;
    td_seeds.addEvent("click", function(){window.open(torrent.href);});
    torrent.element.appendChild(td_seeds);
    
    var td_peers = $(this.element_stockpile.td.cloneNode(false));
    td_peers.innerHTML = torrent.peers;
    td_peers.addEvent("click", function(){window.open(torrent.href);});
    torrent.element.appendChild(td_peers);
    
    var td_engine = $(this.element_stockpile.td.cloneNode(false));
    td_engine.className = torrent.engine;
    td_engine.innerHTML = engine;
    td_engine.addEvent("click", function(){window.open(torrent.href);});
    torrent.element.appendChild(td_engine);
  
  	// RESULTS TOTAL
  	if ($('resultstotal').innerHTML == "") { $('resultstotal').innerHTML = 0; $('pagination_offset').style.display = 'inline'; }
   	$('resultstotal').innerHTML = parseInt($('resultstotal').innerHTML) + 1;
  
    return torrent;
  },

  add_torrents_to_table: function( passed_torrents, callback ) {
    if ($type(passed_torrents) != 'array') {
      this.torrents_chain.chain( callback );
      return;
    }
    var torrents = $A();
    var torrent;
    while(torrent = passed_torrents.shift()){
      if (!torrent.anchor || !torrent.seeds || torrent.seeds > 1000000 || torrent.size == "0 MB") continue;
      torrent = this.prep_torrent( torrent );
      if (torrent && torrent.element) torrents.unshift( torrent );
    }
    if (torrents.length > 0) {
    torrents.sort(function(a,b){
      return b.seeds - a.seeds;
    });
    var trs = this.tbody.getElements('tr');
    if ( trs.length == 0 ) {
      this.first_torrent_to_tr( torrents.shift() );
      trs = this.tbody.getElements('tr');
    }
    if ( torrents.length > 0 ){
    for (var i=0;i<trs.length;i++){
      if ( parseInt(trs[i].getElementsByTagName('td')[3].getText()) <= torrents[0].seeds ){
        this.torrents_chain.chain( this.add_torrent_to_tr.pass( [torrents.shift(), i], this ) );
        i = i-1;
        if ( torrents.length == 0 ) break;
      }
    }
    if ( torrents.length > 0 ){
      this.torrents_chain.chain( this.add_torrent_to_tr.pass( [torrents[0], trs.length], this ) );
      if (torrents.length > 1)
      for (var i=1;i<torrents.length;i++){
        this.torrents_chain.chain( this.add_torrent_to_tr.pass( [torrents[i], trs.length+i], this) );
      }
    }
    }
    }
    this.torrents_chain.chain( callback );
    trs = false;
  }  

});
