var JSONToolTip = Class.create({
  initialize: function(JSON_object, shell) {
    // this.toolTipData = $H(JSON_object.evalJSON());
    this.toolTipData = $H(JSON_object)
    defaultOptions = {
      leftOffsetSwitch: 400 
    };
    
    this.tooltip = {right: $('tooltip-right'), left: $('tooltip-left')};
    this.tooltip.right.observe('mouseout', this.tooltip_mouseevent_handler.bind(this));
    this.tooltip.left.observe('mouseout', this.tooltip_mouseevent_handler.bind(this));
    this.tooltip.right.observe('mouseover', this.tooltip_mouseevent_handler.bind(this));
    this.tooltip.left.observe('mouseover', this.tooltip_mouseevent_handler.bind(this));
    this.activeTooltip;
    this.activeThumbnail;
    
    this.shell = shell;
  },
  
  render: function(el) {    
    var data = this.toolTipData.get(el.id);
    if (!data) return;
    
    var shellLeft = this.shell.cumulativeOffset().left;
    var offsetLeft;
    var offsetTop = -45;

    if ((el.cumulativeOffset().left - shellLeft) > 500) {
      this.activeTooltip = this.tooltip.left;
    }
    else {
      this.activeTooltip = this.tooltip.right;
      offsetLeft = 93;
    }
    
    var inactiveTooltip = this.activeTooltip == this.tooltip.left ? this.tooltip.right : this.tooltip.left;
    if (inactiveTooltip.visible()) inactiveTooltip.fade({duration: .1});
        
    this.activeTooltip.down('h6').update(data.title.truncate(50, '...')).next('p').update(data.price);
    
    if (this.activeTooltip == this.tooltip.left) offsetLeft = 25-(this.activeTooltip.getWidth());
    
    this.activeTooltip.clonePosition( 
      el, 
      { setHeight: false, setWidth: false, offsetLeft: offsetLeft, offsetTop: -45 }
    );
    // tooltip.show();
    this.activeTooltip.appear({duration: .25});
    this.activeThumbnail = el;
  },
  
  hide: function() {
    if (this.tooltip.right.visible()) this.tooltip.right.fade({duration: .1});
    if (this.tooltip.left.visible()) this.tooltip.left.fade({duration: .1});
    // this.activeThumbnail.removeClassName('active');
  },
  
  tooltip_mouseevent_handler: function(e) {
    if (e.type == 'mouseover') this.activeThumbnail.addClassName('active');
    else {
      var test = this.activeTooltip.descendants().any(function (n) {
        return n == e.relatedTarget;
      });
      if (!test && !e.relatedTarget.match('img') && (e.relatedTarget != this.activeTooltip)) this.hide();
      this.activeThumbnail.removeClassName('active');
    }
  }
});











