// Original: http://htmlcoder.visions.ru/js/t
// Partially rewritten and moved to jQuery 1.3.2

(function($)
{

var tooltip = {
	attr_name: "tooltip",
	blank_text: "(откроется в новом окне)",
	newline_entity: new RegExp("[\n]|[ ]{2}", "g"),
	max_width: 350,
	delay: 50,

	Container: document.createElement("div"),
	timeout: null,
	is_visible: false,
	
	Window: $(window),
	Document: $(document),
	
	w_width:  0,
	w_height: 0,
	
	move_handler: null,
	show_handler: null,
	hide_handler: null,
	
	init: function()
	{
		this.Container.setAttribute("id", "tooltip");
		this.Container.style.display = "none";
		
		document.body.appendChild(this.Container);
		var a = document.all ? document.all : document.getElementsByTagName("*");
		
		this.move_handler = __Bind2(this.onMouseMove, this);
		var show = this.show_handler = __Bind2(this.showContainer, this);
		var hide = this.hide_handler = __Bind2(this.hideContainer, this);
		
		for (var i=0; i<a.length; i++)
		{
			var element = a[i];
			
			var tooltip_title = element.getAttribute("title");
			if (typeof tooltip_title !== "string"){ continue; }
			
			if (element.getAttribute("target") === "_blank" && this.blank_text !== "")
			{
				tooltip_title = (tooltip_title !== "") ? tooltip_title+" "+this.blank_text : this.blank_text;
			}
			
			if (tooltip_title !== "")
			{
				element.setAttribute(this.attr_name, tooltip_title);
				
				// Удаление аттрибута "title" чтобы не всплывала стандартная подсказка в браузере
				element.removeAttribute("title");
				
				$(element).mouseenter(show).mouseleave(hide);
			}
		}
		
		this.updateWindowSize();
		//this.moveContainer(-99, -99);
	},
	
	showContainer: function(e)
	{
		var d = window.event ? window.event.srcElement : e.target;
		if (!d.getAttribute(this.attr_name)){ return; }
		
		// Подключение отслеживания движений мыши
		this.Document.bind("mousemove", this.move_handler);
		this.Window.bind("scroll", this.hide_handler);
		
		var s = d.getAttribute(this.attr_name);
		
		if (this.newline_entity)
		{
			s = s.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;");			
			s = s.replace(this.newline_entity, "<br />");
			
			this.Container.innerHTML = s;
		}
		else
		{
			if (this.Container.firstChild){ this.Container.removeChild(this.Container.firstChild); }
			
			this.Container.appendChild(document.createTextNode(s));
		}
		
		this.Container.style.width = "auto";
		this.timeout = setTimeout(__Bind2(function(){ this.display = ""; this.visibility = "visible"; }, this.Container.style), this.delay);
		
		this.is_visible = true;
	},
	
	hideContainer: function()
	{
		// Лучше сначала скрыть элемент, а потом уже отсоединять обработчик, т.к. процесс 
		// отсоединения может немного подтормаживать при этом контейнер будет долше оставаться видимым.  
		this.Container.style.visibility = "hidden";
		
		// Если контейнер скрыт, отсоединить обработчик события чтобы не работал впустую
		this.Document.unbind("mousemove", this.move_handler);
		this.Window.unbind("scroll", this.hide_handler);
		
		if (!this.newline_entity && this.Container.firstChild){ this.Container.removeChild(this.Container.firstChild); }
		
		clearTimeout(this.timeout);
		this.is_visible = false;
		
		//this.moveContainer(-99, -99);
	},
	
	onMouseMove: function(e)
	{
		if (!this.is_visible){ return; }
		
		var x = e.pageX;
		var y = e.pageY;
		
		var w_width  = this.w_width;
		var w_height = this.w_height;
		var style    = this.Container.style;
		
		style.width = ((this.max_width) && (this.Container.offsetWidth > this.max_width))
			? this.max_width+"px"
			: "auto";
		
		var t_width = this.Container.offsetWidth;
		var t_height = this.Container.offsetHeight;
		
		style.left = (x + t_width > w_width)   ? w_width - t_width+"px"   : x+10+"px";
		style.top  = (y + t_height > w_height) ? w_height - t_height+"px" : y+18+"px";
	},
	
	moveContainer: function(x, y)
	{
		this.onMouseMove({pageX: x, pageY: y});
	},
	
	updateWindowSize: function()
	{
		var w = $(document.body);
		
		this.w_width  = w.innerWidth();
		this.w_height = w.innerHeight();
	}
}

// Функция убрана сюда чтобы исключить зависимость от soda.js
var __Bind2 = function(m, o, p){ return function(){ return m.apply(o, (p === undefined) ? arguments : p); }; }

// Временная заплатка пока не прикручены нормальные модальные окна
var p = window.prompt;
window.prompt = function(){ tooltip.hideContainer(); return p.apply(this, arguments); }

$(document).ready(__Bind2(tooltip.init, tooltip));
$(window).load(__Bind2(tooltip.init, tooltip)).resize(__Bind2(tooltip.updateWindowSize, tooltip));

})(jQuery);


