$(document).ready(function() {
  $(document).find("[title]").each(function() {
  	if ($(this).attr("title")) {
  		$(this).attr("rel", $(this).attr("title"));
  		$(this).attr("title", "");
  		$(this).mousemove(tooltip_show);
  		$(this).mouseout(tooltip_hide);
  	}
  });
});

function add_tooltip(elm) {
	var txt = $.trim(elm.attr("title"));
	if (txt) {
		set_tooltip(elm, txt, false);
		elm.attr("title", "");
	}
}

function set_tooltip(elm, data, show) {
	$(elm).attr("rel", data);
	$(elm).mousemove(tooltip_show);
	$(elm).mouseout(tooltip_hide);
	if (show) {
		tooltip_show(elm);
	}
}

function clear_tooltip(elm) {
  $(elm).unbind("mousemove");
  $(elm).unbind("mouseout");
  $("#tooltip").hide();
}

var tooltip_for;
var tooltip_el;
var doc_el;
var tooltip_width;
var doc_width;

function tooltip_show(e) {
	if (tooltip_for != this) {
		if (!$(this).attr("rel")) {
			return;
		}
		$("#tooltip").hide();
		$("#tooltip").html($(this).attr("rel"));

	  tooltip_for = this;
	  $("#tooltip").show();
		tooltip_el = $("#tooltip");
		doc_el = $(document);
		doc_width = doc_el.width();
		tooltip_width = tooltip_el.width();
	}
	if (e.pageX + 20 + tooltip_width > doc_width - 20) {
    tooltip_el.css("left", doc_width - tooltip_width - 20);
	} else {
    tooltip_el.css("left", e.pageX + 20);
  }
	tooltip_el.css("top", e.pageY + 22);
}

function tooltip_hide() {
  tooltip_for = false;
	$("#tooltip").hide();
}

function show_hide(ln, eln) {
	$(ln).click(function() {
		if ($(eln).css("display") == "none") {
			$(eln).slideDown('fast');
		} else {
			$(eln).hide();
		}
		return false;
	});
}


