BlasphemyBox = Class.create();
BlasphemyBox.prototype = {
  initialize: function() {
    this.blasphemy_box = $('blasphemy_box');

    this.data = blasphemy_box_data;
    this.buildPage();

    Event.observe(this.blasphemy_box, 'mousemove', this.handleMouseMove.bindAsEventListener(this));
    Event.observe(this.blasphemy_box, 'mouseover', this.handleMouseOver.bindAsEventListener(this));
    Event.observe(this.blasphemy_box, 'mouseout', this.handleMouseOut.bindAsEventListener(this));

    this.timeout = null;
  
    this.tooltip = $('tooltip_container');
    this.tooltip_text = $('tooltip');
    this.tooltip.hide();
    this.tooltip.absolutize();
    document.body.appendChild(this.tooltip);
  },

  generateItem: function(img, text, link) {
    return '<div class="img_container" text="' + text + '"><a href="' + link + '" target="_BLANK"><img src="/images/blasphemy_box/' + img + '" /></a></div>';
  },
  
  buildPage: function() {
    this.data.sort(function() {return (Math.round(Math.random())-0.5);});
    this.data.each(function(item) {
      this.blasphemy_box.insert({top: this.generateItem(item.image, item.text, item.link)});
    }.bind(this));
  },
  
  handleMouseMove: function(e) {
    var x = Event.pointerX(e) + 25;
    var y = Event.pointerY(e) + 25;

    var viewport = document.viewport.getDimensions();
    
    var dimensions = this.tooltip.getDimensions();
    
    var scrollOffsets = document.viewport.getScrollOffsets();
    
    var viewportX = x - scrollOffsets[0];
    var viewportY = y - scrollOffsets[1];
    
    if ( (viewportY + dimensions.height) > viewport.height ) {
      y = y - 50 - dimensions.height;
    }
    
    if ( (viewportX + 50 + dimensions.width) > viewport.width ) {
      x = x - 50 - dimensions.width;
    }
    
    this.tooltip.setStyle({
      left: x + 'px',
      top: y + 'px'
    });
    
  },
  
  handleMouseOver: function(e) {
    var el = Event.element(e);
    if (el.tagName == 'IMG' || el.tagName == 'A') {
      el = el.up('div');
    }
    
    if (this.timeout) {
      clearTimeout(this.timeout);
      this.timeout = null;
    }
    
    if (el.hasClassName('img_container')) {
      if (Prototype.Browser.IE) { el.addClassName('hover'); }
      this.tooltip_text.update(el.readAttribute('text'));
      this.tooltip.setStyle({
        height: this.tooltip_text.getDimensions().height + 'px'
      });
    }
    
    this.tooltip.show();
  },
  
  handleMouseOut: function(e) {
    var el = Event.element(e);
    if (el.tagName == 'IMG' || el.tagName == 'A') {
      el = el.up('div');
    }
    if (Prototype.Browser.IE && el.hasClassName('img_container')) { el.removeClassName('hover'); }
    var tooltip = this.tooltip;
    this.timeout = setTimeout(function() { tooltip.hide(); }, 100);
  }

}

