/**
 * @author Thomas Rabaix <thomas.rabaix@gmail.com>
 * @copyright 2008 Allomatch.com
 * @package Subscription
 * @license MIT
 * @url http://www.allomatch.com/
 * @dependencies prototype.js 1.5.1+, effects.js, gliders.js
 */
 
var BarAds = {
  PERIODE   : 8,
  DURATION  : 1,
  
  elms      : null,
  counters  : new Hash(),
  url       : '/subscriptions.php',
  
  tournoi   : null,
  sport     : null,
  equipe    : null,
  
  // fix bug on the match page, the object is load event is executed two times 
  loaded    : false,
  
  load: function()
  {
    if(BarAds.loaded)
    {
      return;
    }
    
    BarAds.loaded = true;
    
    BarAds.elms = $$('div.subscription');
    BarAds.elms.each(function(elm, index) {
      BarAds.counters.set(elm.id, 0);
    });
    
   
    if($('glider-tournoi'))  BarAds.tournoi = new Glider('glider-tournoi', {duration:BarAds.DURATION});
    if($('glider-sport'))    BarAds.sport   = new Glider('glider-sport', {duration:BarAds.DURATION});
    if($('glider-equipe'))   BarAds.equipe  = new Glider('glider-equipe', {duration:BarAds.DURATION});
    
    if(BarAds.tournoi || BarAds.sport || BarAds.equipe) {
      BarAds.updater = new PeriodicalExecuter(function(){
        BarAds.next()
      }, BarAds.PERIODE);
    } 
    else // homepage
    {
      BarAds.count();
    }
  },
  
  count: function()
  {
    BarAds.elms.each(function(elm, index) {
      if(elm.style.visibility == 'visible')
      {
        var value = BarAds.counters.get(elm.id);
        BarAds.counters.set(elm.id, ++value);
      }
    });
  },
  
  unload: function()
  {
    pic = new Image(1,1); 
    pic.src= BarAds.url + '?' + BarAds.counters.toQueryString();
  },
  
  addCount: function(elm)
  { 
    elm.cleanWhitespace();
    
    // the glider.current refer to the 'section' div. which is the parent of the bar div
    var child = elm.firstChild;
    
    var value = BarAds.counters.get(child.id);
    
    value++;

    BarAds.counters.set(child.id, value);
  },
  
  next: function()
  {
    if(BarAds.tournoi) BarAds.tournoi.next();
    if(BarAds.sport)   BarAds.sport.next();
    if(BarAds.equipe)  BarAds.equipe.next();
  },
  
  previous: function()
  {
    if(BarAds.tournoi) BarAds.tournoi.previous();
    if(BarAds.sport)   BarAds.sport.previous();
    if(BarAds.equipe)  BarAds.equipe.previous();
  }
  
}
 
Event.observe(window, 'load',   BarAds.load,   false);
Event.observe(window, 'unload', BarAds.unload, false);
