ODIL_Initializer.add_selector_with_action('.has_tooltip', function(element) {
	new Tooltip().add_tooltip_to_element(element);
});

ODIL_Initializer.add_selector_with_action('.tooltip', function(element) {
	new Tooltip().initialize_tooltip(element);
});


var Tooltip = Class.create(ODIL_Base, {
	namespace: function($super) {
		return $super() + 'tooltip';
	},
	
	element: null,
	
	defaults: {
		tooltip: null,
		padding: 0,
		attachment: 'bottom',
		content: '',
		duration: 0.3
	},
	
	add_tooltip_to_element: function(element) {
		this.element = element;
		this.load_properties(element);
		this.properties.set('tooltip', $(this.properties.get('tooltip_id')))
		this.load_properties(this.properties.get('tooltip'));
		this.load_properties(element);
		
		var that = this;
		element.observe('mouseover', function(event) {
			var top;
			var left;
			
			var tooltip_content = that.properties.get('content');
			
			$H(tooltip_content).each(function(pair) {
				if(pair.key == 'self') {
					that.properties.get('tooltip')[pair.value.attribute] = pair.value.value;
				}
				else {
					that.properties.get('tooltip').down(pair.key)[pair.value.attribute] = pair.value.value;
				}
			});
			
			switch (that.properties.get('attachment')) {
				case 'bottom':
					top = that.element.cumulativeOffset().top + that.element.getHeight() + that.properties.get('padding');
					left = that.element.cumulativeOffset().left + that.element.getWidth()/2 - that.properties.get('tooltip').getWidth()/2;
					break;
				case 'left':
					top = that.element.cumulativeOffset().top + that.element.getHeight()/2 - that.properties.get('tooltip').getHeight()/2;
					left = that.element.cumulativeOffset().left - that.properties.get('tooltip').getWidth() - that.properties.get('padding');
					break;
				case 'right':
					top = that.element.cumulativeOffset().top + that.element.getHeight()/2 - that.properties.get('tooltip').getHeight()/2;
					left = that.element.cumulativeOffset().left + that.element.getWidth() + that.properties.get('padding');
					break;
				default:
					break;
			}
			
			top -= that.element.cumulativeScrollOffset().top - document.viewport.getScrollOffsets().top;
			left -= that.element.cumulativeScrollOffset().left - document.viewport.getScrollOffsets().left;
			
			that.properties.get('tooltip').setStyle({
				top: Math.max(top, 0) + "px",
				left: Math.max(left, 0) + "px"
			});
			
/* 			$('test')['src'] = 'bottom.png'; */
/* 			$('test2')['innerHTML'] = 'Hi'; */
			that.properties.get('tooltip').show();
		});
		
		element.observe('mouseout', function(event) {
			that.properties.get('tooltip').hide();
		});
	},
	
	initialize_tooltip: function(element) {
		element.hide();
	}
});
