});

$(window).on('action:posts.loaded action:topic.loaded action:posts.edited', function() {
	initTooltips();
});

$(window).on('action:ajaxify.contentLoaded', function(){
	$('.item-tooltip').hide();
});

function initTooltips() {
	$('.vanilla-tooltip').each(function(tooltip){
		var name = $(this).attr('data-name');
		var $this = $(this);
		$.getJSON('http://api.theorycraft.fi/v1/item', {name: name}, function(response){
			$this.text('['+response.data[0].name+']').attr('rel', 'item='+response.data[0].entry).addClass('q'+response.data[0].quality);
			ajaxify('http://db.vanillagaming.org/ajax.php?item='+response.data[0].entry+'&power');
		});
		$this.mouseenter(function(){
			showTooltip($this.data('id'), $this.data('tooltip'));
		}).mouseleave(function(){
			$('.item-tooltip').hide();
		});	
	});

	$(document).mousemove(function(event) {
		$('.item-tooltip').css({
			left: event.pageX+10,
			top: event.pageY+10
		});
    });
}

function showTooltip(id, data) {
	if(!$('.item-tooltip#'+id).length) {
		var iconUrl = typeof data.icon == 'undefined' ? '' : 'http://db.vanillagaming.org/images/icons/medium/'+data.icon.toLowerCase()+'.jpg';
		var $tooltip = $('<div id="'+id+'" class="item-tooltip"><p style="background-image: url('+iconUrl+');"><span></span></p><table><tr><td>'+data.tooltip_enus+'</td><th style="background-position: 100% 0%;"></th></tr><tr><th style="background-position: 0% 100%;"></th><th style="background-position: 100% 100%;"></th></tr></div>');
		$tooltip.css('visibility', 'visible').appendTo('body').show();
	} else $('.item-tooltip#'+id).show();
}

function ajaxify(url) {
	$('<script type="text/javascript" src="'+url+'"></script>').appendTo('body');
}

$WowheadPower = {
	registerItem: function(a,b,item) {
		$('a.vanilla-tooltip[rel="item='+a+'"]').data('tooltip', item).data('id', a);
	}
}
$('document').ready(function() {	
	initTooltips();