var HelpTips = new Class({

	getOptions: function(){
		return {
			offsets: {'x': 0, 'y': 5}
		};
	},

	initialize: function(elements, options){
		this.setOptions(this.getOptions(), options);
		$each(elements, function(el){
			this.build($(el));
		}, this);
		if (this.options.initialize) this.options.initialize.call(this);
	},

	build: function(el){
		var tip = $('for-' + el.id);
		el.addEvent('click', function(event){
			this.locate(el, tip, event);
			tip.setStyle('visibility', 'visible');
		}.bindWithEvent(this));
		var close = $('for-' + el.id + '-close');
		if(close){
			close.addEvent('mousedown', function(event){
				tip.setStyle('top', '-9999px');
				tip.setStyle('visibility', 'hidden');
			}.bindWithEvent(this));
		} else{
			var cls = new Element('div').addClass('help-close').injectInside(tip).setHTML('<a href="#">Close</a>');
			cls.addEvent('mousedown', function(event){
				tip.setStyle('top', '-9999px');
				tip.setStyle('visibility', 'hidden');
			}.bindWithEvent(this));
		}
	},

	locate: function(el, tip, event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tipco = {'x': el.offsetWidth, 'y': el.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		var tipWidth, tipHeight;
		if (tip.currentStyle) {
			tipWidth = tip.currentStyle.width;
			tipHeight = tip.currentStyle.height;
		} else if (window.getComputedStyle) {
			tipWidth = window.getComputedStyle(tip, null).width;
			tipHeight = window.getComputedStyle(tip, null).height;
		}
		
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tipco[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tipco[z];
			if ((z == 'x' && (pos + parseInt(tipWidth)) > win[z])) {
				pos = win[z] - parseInt(tipWidth) * 1.2;
			}
			tip.setStyle(prop[z], pos + 'px');
		};
		event.stop();
	}
	
});


HelpTips.implement(new Events);
HelpTips.implement(new Options);

addLoadEvent(load);
function load() {
	new HelpTips($$('.help-link'));
}