/**
 * Diary Bubble
 * Code for displaying diary info
 *
 */
 
var DiaryBubble = {
    
  setup: function() {
    var db = DiaryBubble;
    db.bubble = $e('diary-bubble');
    db.num = $e('db-num');
    db.cache = [];
    db.fired = [];
    // save initial state
    db.startState = $j(db.bubble).find('.js-loader').get(0);
    // save initial height
    db.startHeight = $j(db.bubble).height();
    // setup diary bubble html
    $j(db.bubble)
    .hide()
    // setup diary bubble listeners
    .mouseleave(function() {
      $j(db.bubble).hide();
    });
    
    // setup listeners on links
    $j('ul.di-month li a').mouseover(function() {
      if ($j(this).parent().hasClass('active')) {
        // record that we are looking at a new bubble
        db.currentBubble = this;
        Log.debug('mouse over diary day');
        
        // if we've already fetched the information...
        if (db.cache[this.href]) {
          $j(db.bubble).find('.js-loader, table').replaceWith(db.cache[this.href]);
        }
        // ...or if we've already requested the info
        else if (db.fired[this.href]) {
        }
        // ...else get the info
        else {
          // make sure loader is displayed
          $j(db.bubble).find('table').replaceWith(db.startState);
          // register the request
          db.fired[this.href] = true;
          // send ajax request for diary info
          $j.get(this.href, null, function(data, response) {
            // 'this' is now the XMLHttpRequest object
            Log.debug('current response = ' + response);            
            // cache returned data
            db.cache[this.url] = data;
            // check if user is still viewing the same bubble
            if (db.currentBubble.href == this.url) {
              // get current position
              var pos = $j(db.currentBubble).position();
              // display returned data
              $j(db.bubble)
                .find('.js-loader')
                .replaceWith(data)
              .end()
              .css('top', pos.top - $j(db.bubble).height() - 18);
            }
          });
        }
        var pos = $j(this).position();
        // change number and href to match
        db.num.innerHTML = this.innerHTML;
        db.num.href = this.href;
        // change title in bubble
        $j(db.bubble).find('p a').attr('href', this.href).text(this.title);
        $j(db.bubble)
        .css({
          left: pos.left - 202,
          top: pos.top - $j(db.bubble).height() - 18
        })
        .show();
      }
    })
    .click(function() {
      if (!$j(this).parent().hasClass('active')) return false;
    });
  }
};

Finish.addTask(DiaryBubble.setup, 'DiaryBubble.setup');