var ToolTip = new Class({
	initialize: function(element) {
		this.element = element;
		this.attachMouseHandlers();
	},
	
	attachMouseHandlers: function() {
		var tt = this;
		this.element.addEvents({
			"mouseenter": function(event) {
				var tooltip = tt.createToolTip();
				tooltip.setStyles({
						"opacity": 0,
						"left": 0,
						"top": 0
					})
					.inject(document.body);
				var x = event.page.x + 10;
				var y = event.page.y + 10;
				var size = tooltip.getSize();
				var windowSize = window.getSize();
				x = Math.max(Math.min(x, windowSize.x - size.x - 5), 0);
				y = Math.max(Math.min(y, windowSize.y - size.y - 5), 0);
				tooltip.setStyles({
					"left": x,
					"top": y,
					"opacity": 1
				});
				tt.element.store("tooltip", tooltip);
			},
			
			"mouseleave": function() {
				tt.element.retrieve("tooltip").dispose();
			}
		});
	}
});

var TextToolTip = new Class({
	Extends: ToolTip,

	initialize: function(element, title, text) {
		this.parent(element);
		this.title = title;
		this.text = text;
	},
	
	createToolTip: function() {
		var contentsEl = new Element("div", { "class": "toolTip-contents" });
		this.createTextElements().each(function(el) {
			contentsEl.grab(el);
		});
		return new Element("div", { "class": "toolTip" })
			.grab(new Element("div", { "class": "toolTip-title" })
				.appendText(this.title))
			.grab(contentsEl);
	},
	
	createTextElements: function() {
		var elements = new Array();
		this.text.split("\\n").each(function(part) {
			if (part.length > 0) {
				elements.push(document.newTextNode(part));
			}
			elements.push(new Element("br"));
		});
		if (elements.length > 0) {
			elements.pop();
		}
		return elements;
	}
});

var ItemToolTip = new Class({
	Extends: ToolTip,
	
	initialize: function(element, itemId) {
		this.parent(element);
		this.itemId = itemId;
	},
	
	createToolTip: function() {
		return new Element("div", { "class": "itemToolTip" })
			.grab(new Element("img", { "src": "http://wow.buffed.de/items/gif/" + this.itemId + ".gif" }));
	}
});

window.addEvent("domready", function() {
	$$(".hasToolTip").each(function(el) {
		new TextToolTip(el, el.getAttribute("toolTipTitle"), el.getAttribute("toolTipText"));
	});

	$$(".hasItemToolTip").each(function(el) {
		new ItemToolTip(el, el.getAttribute("blizzardItemId"));
	});
});
