/**
 * @author Mat Weir <mat.weir@xebidy.com>
 * @copyright 2008 Xebidy Strategic Design
 * @package TipHandler
 * @license MIT
 * @url http://xebidy.com/code/tiphandler/
 * @version 0.1
 */
 
var TipHandler = Class.create({
  
  tooltip: null,
  options: { },
  counter: 0,
  counterOn: false,
  effect: null,
  
  initialize: function(selector, options) {
  	
  	var me = this;
  	
  	this.options = Object.extend({
  		offsetLeft: -4,
  		offsetTop: -46
  	}, options);
  	
  	this.createTip();
  	
  	setInterval(me.incrementCounter.bind(me), 2000);
  	
    this.elements = $$(selector);
		
		if (!this.elements) return;
		
    this.elements.each(function(i) {
    	i.observe('mouseover', me.showTip.bind(me));
    	i.observe('mouseout',  me.startCountdown.bind(me));
    });
  },

  createTip: function() {
  	if (this.tooltip) return;
  	
    $$('body').first().insert({ bottom: "<div id='tooltip'><p></p><span></span></div>" });
    this.tooltip = $('tooltip');
		this.tooltip.hide();
  },
  
  showTip: function(event) {
  	var element = Event.element(event);
	
  	if (title = element.readAttribute('alt')) {
  	
			if (this.effect) this.effect.cancel();
			this.tooltip.setOpacity(1);
		
  		this.tooltip.down('p').update(title);
  		
  		this.tooltip.setStyle({ 
  			left: (element.up('a').cumulativeOffset()[0] + this.options.offsetLeft) + 'px',
  			top:  (element.up('a').cumulativeOffset()[1] + this.options.offsetTop) + 'px'
  		});
  		this.tooltip.show();
  		this.stopCountdown();
  	}
  	return false;
  },
  
  hideTip: function(event) {
  	this.effect = Effect.Fade(this.tooltip, { duration: 1 });
  },
  
  incrementCounter: function() {
  	this.counter++;
  	if (this.counter > 0 && this.counterOn == true) {
  		this.hideTip();
  		this.stopCountdown();
  	}
  },
  
  startCountdown: function() {
		this.counter = 0;
		this.counterOn = true;
  },
  
  stopCountdown: function() {
  	this.counterOn = false;
  }
	
});
