YUI().use('anim','node','event','io-base',function(Y) {
  Y.one('body').addClass('js');
  Y.on("domready", function(e){
    var xy;
    var countries = Y.one('#countries');
    countries.prepend('<p class="copy">Check and uncheck the different countries to see or hide their medal scores. Click a country code or a year to see the detail statistics.</p>'); 
    countries.append('<li class="but"><button id="all">check all</button><button id="none">uncheck all</button></li>');
      Y.one('#bd').append('<div id="hover"></div>'); 
      Y.one('#bd').append('<div id="details"><button>close</button><div id="content"></div></div>'); 
      var hover = Y.one('#hover');
      var details = Y.one('#details');
      var contents = Y.one('#details div');
      var medals = Y.one('#medals');
      details.setStyle('display','none');
      medals.delegate('mouseover',function(e){
        if(this.one('p')){
        var text = this.one('p').get('innerHTML');
          hover.setX(this.getX()+30);
          hover.setY(this.getY()+30);
          hover.set('innerHTML',text);
        } else {
          hover.setXY([-20000,0]);
        }
      },'td');
      medals.delegate('mouseout',function(e){
        hover.setXY([-20000,0]);
    }); 
    countries.delegate('click',function(event){
      if(this.get('id')=='none'){
        Y.all('#medals tbody tr').setStyle('display','none');
        Y.all('#countries input').set('checked',false);
      } else {
        Y.all('#medals tbody tr').setStyle('display','');
        Y.all('#countries input').set('checked',true);
      }
    },'button');
    countries.delegate('click',function(event){
      if(this.get('id')!=''){
        var t = Y.one('#c'+this.get('id'));
        if(this.get('checked')){
          t.setStyle('display','');
        } else {
          t.setStyle('display','none');
        }
      }
    },'input');
    
    medals.delegate('click',function(event){
      event.preventDefault();
      if(this.get('href')!=''){
        var url = this.get('href').replace('detail.php','table.php');
        xy = this.getXY();
        Y.io(url,{on:{
          start:function(id,o,args){},
          complete:function(id,o,args){
            details.setStyle('display','block');
            contents.set('innerHTML',o.responseText);
            if(o.responseText.indexOf('<!--year')!=-1){
              details.setX(xy[0]+60);
              details.setY(xy[1]-30);
            } else {
              details.setX(medals.getX()+100);
              details.setY(xy[1]+30);
            }
          }
          }
        });
      }
    },'a');
    Y.one('#details button').on('click',function(event){
      event.preventDefault();
      details.setStyle('display','none');
    });
  });
});
