$(document).ready(function() {
	if ($.browser.msie && navigator.appVersion.match(/ MSIE [345]/)) return;

	$('body').append('<div id="balloon" class="top"><div id="balloon-inner"><div id="balloon-top"></div><div id="balloon-content"></div><div id="balloon-bottom"></div><div id="balloon-loading"></div><div id="balloon-corner"></div></div></div>');

	$('#content').click(load_balloon);
	$('#balloon-top').click(hide_balloon);

	$('#balloon').click(function(e) {
		var t = e.target;
		var lnk = this.$t;
		while (t && t.nodeType == 1 && t.tagName.toLowerCase() != 'div' && t.tagName.toLowerCase() != 'a') {
			t = t.parentNode;
		}
		if (!t || t.tagName.toLowerCase() != 'a' || !t.href || !$(t).hasClass('via-ajax')) return;
		if (lnk) lnk.ajaxres = undefined;
		$.get(t.href, {ajax: 'balloon'}, function(data) {
			$('#my-program p').html('<a href="/my/">' + data + '</a>');
			$(t).hide();
		});
		return false;
	});
});

function load_balloon(e) {
	var t = e.target;
	while (t.tagName.toLowerCase() != 'a' && t.tagName.toLowerCase() != 'div') t = t.parentNode;
	if (t.tagName.toLowerCase() != 'a' || !t.rel) return;

	var data = {x: e.pageX, y: e.pageY, t: t};
	data.cl = t.parentNode.parentNode.parentNode.className;
	if (typeof t.ajaxres == 'string') {
		$('#balloon-content').html(t.ajaxres);
		show_balloon(data);
	} else {
		$('#balloon-content').html('<div class="spacer"></div>');
		show_balloon(data);
		$('#balloon-content').load(t.rel + '?ajax=balloon', function(res) {show_balloon(data, res)});
	}
	return false;
}

function show_balloon(data, res) {
	var b = $('#balloon');
	var w = b.width();
	var h = b.height();
	b.removeClass();
	if ('undefined' != typeof res) {
		data.t.ajaxres = res;
	}
	if (data.x + w + 20 < document.documentElement.scrollWidth) {
		b.get(0).style.left = data.x + 10 + 'px';
	}
	else {
		b.addClass('right');
		b.get(0).style.left = (data.x - w - 10) + 'px';
	}
	if (((data.y - h) < 350) || ((data.y - document.documentElement.scrollTop - h) < 0)) {
		b.addClass('top');
		b.get(0).style.top = data.y - 53 + 'px';
	}
	else {
		b.addClass('bottom');
		b.get(0).style.top = (data.y - h + 30) + 'px';
	}
	if (data.cl && data.cl.match('recommended-item')) {
		$('#reclink').show();
	}
	b.show();
}

function hide_balloon() {
	$('#balloon').hide();
	$('#tip').hide();
	$('#reclink').hide();
}

$(function() {
	$('#unauthedbuttons').live('click', function() {
		$('#tip').show();
	});
});
