var Balloons = new Class({
	Implements: [Options, Events],
	
	options: {
		office: 'office',
		area: 'area.balloon'
	},
	initialize: function(options) {
		this.setOptions(options);
		$$(this.options.area).each(this.createBalloon.bind(this));
	},
	
	createBalloon: function(el) {
		el.offset = {
			x: el.get('rel').split(',')[0],
			y: el.get('rel').split(',')[1]
		};
		
		el.balloon = new Asset.image('/assets/images/balloons/' + el.get('id') + '.png', {
			styles: {
				position: 'absolute',
				display: 'none',
				cursor: 'pointer'
			}
		});
		
		el.addEvents({
			mouseenter: this.showBalloon,
			mouseleave: this.hideBalloon
		});
		
		el.getPosition = function() {
			return $('office').getPosition()
		}
	},
	
	showBalloon: function(event) {		
		if (!this.balloon.trans) {
			this.balloon.trans = {
				height: this.balloon.height
			};
			
			this.balloon.addEvents({
				'mouseover': function(ev) {
					ev.stopPropagation();
					this.overballoon = true;
				}.bind(this),
				
				'mouseout' : function(ev) {
					this.fireEvent('mouseleave');
					this.overballoon = false;
				}.bind(this),
				
				'click' : function() {
					location.href = this.get('href');
				}.bind(this)
			}).set({
				styles : {
					display: '',
					height: 0,
					left: this.getPosition().x + this.offset.x.toInt(),
					top: this.getPosition().y + this.offset.y.toInt() + this.balloon.trans.height
				}
			});
		}
		
		if (this.hiding) {
			clearTimeout(this.hiding);
			this.hiding = false;
		}
		
		if (!this.overballoon) {
			this.balloon.inject(document.body).set({
				'morph': {
					onComplete: function() {},
					duration: 500,
					transition: Fx.Transitions.Bounce.easeOut
				}
			}).morph({
				height: this.balloon.trans.height,
				top: this.getPosition().y + this.offset.y.toInt()
			});
		}
	},
	
	hideBalloon: function(event) {
		this.hiding = (function() {
			if (!this.overballoon) {
				var height = this.balloon.trans.height;
				
				this.balloon.set('morph', {
					onComplete: function() {
						this.setStyles('display', 'none');
					}.bind(this.balloon),
					duration: 100,
					transition: Fx.Transitions.Quad.easeOut
				}).morph({
					height: 0,
					top: this.getPosition().y + this.offset.y.toInt() + height
				});
			}
			
			this.hiding = false;
		}).delay(300, this);
	}
});

window.addEvent('domready', function() {
	new Balloons();
});

