﻿$(document).ready(function() {
	var speed = 'normal';

	$('acronym').each(function(index) {
		var id = $(this).attr('id')
		var len = id.length
		$('#abbr_' + id.substring(len - 32, len)).clone().insertAfter($(this)).hide().attr('id', 'desc_' + $(this).attr('id'));

		$(this).attr('title', '');
	});
	$('acronym a').each(function(index) {
		var text = $(this).text()
		$(this).parent().text(text).end().remove();
	});

	delayed_tip_hide = function(acronym, tip) {
		setTimeout(function() {
			if (!$(acronym).data('is_mouseover')) {
				$(tip).hide(speed);
				$(acronym).removeClass('selected');
			}
		}, 500)
	}

	var hover_timer;

	$('acronym').mouseenter(function(event) {
		var current_acronym = this;

		if(hover_timer) {
			clearTimeout(hover_timer);
			hover_timer = null;
		}
		hover_timer = setTimeout(function() {
			var desc_padding = 10;
			var border_threshold = 20;

			var pos = $(current_acronym).offset();
			var desc = $('#desc_' + $(current_acronym).attr('id'));
			desc.css('height', 'auto');

			var top_offset = $('#body').offset().top;
			var style = {'top': pos.top + $(current_acronym).height() - top_offset, 'left': pos.left}
			var w = desc.width() + desc_padding * 2;
			var h = desc.height() + desc_padding * 2;
			var W = $(window).scrollLeft() + $(window).width();
			var H = $(window).scrollTop() + $(window).height();

			var show = true;

			if(W - pos.left > border_threshold + desc_padding){
				if(pos.left + w + border_threshold > W){
					style['left'] = W - w - border_threshold * 2
				}
			}else{
				show = false;
			}

			if(show && pos.top + $(current_acronym).height() + h + border_threshold > H){
				var new_height = H - pos.top - $(current_acronym).height() - desc_padding * 2 - border_threshold;
				if(new_height > 0){ style['height'] = new_height }else{ show = false };
			}
			desc.css(style);

			$('acronym').removeClass('selected');
			$(current_acronym).addClass('selected');

			$('dl').not(desc).hide(speed);

//			if(show && ($(desc).width() < w)){
//				$(desc).css('width', w);
//			}

			$(current_acronym).data('is_mouseover', true);

			if (show) {
				$(desc).stop(true, true).show(speed, function() {
					if($.browser.msie){$(this).get(0).style.removeAttribute('filter')};
				}).mouseenter(function(){
					$(current_acronym).data('is_mouseover', true);
				}).mouseleave(function(){
					$(current_acronym).data('is_mouseover', false);
					delayed_tip_hide(current_acronym, this);
				})
			}
		}, 500)
	}).mouseleave(function(){
		clearTimeout(hover_timer);

		var tip = $('#desc_' + $(this).attr('id'));

		$(this).data('is_mouseover', false);
		delayed_tip_hide(this, tip);
	});
});