/**
 * Popup for mootools 1.2.1
 * 
 * @license MIT-style license
 * @author Anquetil Manuel <manuel.anquetil [at] baphira.com>
 * @copyright Baphira - http://www.baphira.com
 */
var Popup = new Class({
	
	Implements : [Options],
	
	options: {
		tweak: {x:0,y:0},
		fadeDuration: 500,
		transition: Fx.Transitions.linear,
		stayOnPanelOver: true,
		delay: 100
	},
	
	initialize: function(el, panel, options) {
		this.setOptions(options);
		
		this.el = el;
		this.panel = panel;
		this.firstTime = true;
		this.effect = new Fx.Morph (this.panel, {
			transition: this.options.transition,
			duration: this.options.fadeDuration
		})
		
		el.addEvent('mouseenter', function(e) {
			this.show();
		}.bind(this));
		el.addEvent('mouseleave', function(e) {
			(function() {
				if(!this.options.stayOnPanelOver || !this.isPanelOver) {
					this.hide();
				}
			}.bind(this)).delay(this.options.delay);
		}.bind(this));
		if (this.options.stayOnPanelOver) {
			panel.addEvent('mouseenter', function(e){
				this.isPanelOver = true;
			}.bind(this));
			panel.addEvent('mouseleave', function(e){
				this.isPanelOver = false;
				this.hide();
			}.bind(this));
		}
	},
	
	show: function() {
		if (this.firstTime) {
			this.panel.setStyle('display','block');
			this.panel.inject(document.body);
			
			var top = this.el.getPosition().y - this.panel.getSize().y + this.options.tweak.y;
			var left = this.el.getPosition().x - (this.panel.getSize().x/2).toInt() + this.options.tweak.x;
			
			this.panel.setStyles({
				'opacity': 0,
				'position': 'absolute',
				'top': top + 'px',
				'left': left + 'px'
			});
			this.firstTime = false;
		} else {
			this.panel.setStyle('display','block');
		}
		
		this.effect.cancel();
		this.effect.start({'opacity': [0, 1]});
	},
	
	hide: function() {
		if(!this.firstTime) {
			this.effect.cancel();
			this.effect.start({'opacity': [1, 0]}).chain(function(){
				this.panel.setStyle('display','none');
			}.bind(this));
		}
	}
	
});
