/*
 * Описание:	Всплывающие окна
 * Автор:		Мылтасов Андрей
 * Источник:	b99.ru 
 * Версия:		2.2.3
 */
/************************* toolTip *********************************************************/
function CToolTip()
{
	this.shiftX		= 5;	//Смешение окошка относительно мыши по X
	this.shiftY		= 20;	//Смешение окошка относительно мыши по Y
	this.deltaX		= 20;	//Допуск отклонения мыши от окна по X
	this.deltaY		= 20;	//Допуск отклонения мыши от окна по Y
	this.tSel		= '';	//Выделенный текст
	this.tHtml		= null;	//Выделенный элемент
	//Инициализация
	this.Init = function()
	{
		this.pWin	= document.getElementById('toolTip');			//Указатель на окно
		this.pMsg	= document.getElementById('toolTip-msg');		//Указатель на сообщение
		this.pSwitch= document.getElementById('toolTip-switch');	//Указатель на переключатель
		this.pForm	= document.getElementById('toolTip-form');		//Указатель на форму
		this.pFormC	= document.getElementById('toolTip-control');	//Указатель на упревление формой
		document.onmouseup = eventMouseUp;							//Обработчик выделения
		getCookie('toolTip') ? this.Switch(false): this.Switch(true);
	}
	//Отправка мнения
	this.clickOpinion = function()
	{
		this.pForm.name.value = getCookie('true');
		this.pForm.type.value = 'opinion';
		this.pForm.text.value = 'url: '+ window.location + "\n\n"+'html: '+ this.tHtml + "\n\n"+'select: ' + this.tSel + "\n\n"+'msg: '+ this.pForm.msg.value;
		var func = function()
		{
			if( a.Result != undefined && a.Result.Ok != undefined && a.Result.Ok > 0 ) // Ok?
			{
				a.Form.name.value = a.Form.type.value = a.Form.email.value = a.Form.text.value = a.Form.msg.value = '';
				pToolTip.Hide();
				alert('Спасибо за Ваше мнение');
			}
			else
				alert('Ошибка при отправке. Попробуйте, пожалуйста, позже');
			//Очищаем форму
			a.Del();
		}
		var a = new CAsynForm(this.pForm, func);
		a.Go();
		return true;
	}
	//Отправка сообщения об ошибке
	this.clickError = function()
	{
		if( window.confirm('Отправить информацию об ошибке?') == false )
			return false;
		this.pForm.name.value = getCookie('true');
		this.pForm.type.value = 'error';
		this.pForm.email.value = '';
		this.pForm.text.value = 'url: '+ window.location + "\n\n"+'html: '+ this.tHtml + "\n\n"+'select: ' + this.tSel;
		var func = function()
		{
			pToolTip.Hide();
			if( a.Result != undefined && a.Result.Ok != undefined && a.Result.Ok > 0 ) // Ok?
				alert('Спасибо.'+"\n"+'Информация об ошибке передана в технический отдел');
			else
				alert('Ошибка при отправке. Попробуйте, пожалуйста, позже');
			//Очищаем форму
			a.Form.name.value = a.Form.type.value = a.Form.email.value = a.Form.text.value = a.Form.msg.value = '';
			a.Del();
		}
		var a = new CAsynForm(this.pForm, func);
		a.Go();
		this.pForm.submit();
		return false;
	}
	//Проверка включена форма
	this.isControl = function()
	{
		if( this.pFormC.style.display == 'none' )
			return false;
		return true;
	}
	//Переключатель формы
	this.Control = function(status /*true - open, false - close*/)
	{
		if( typeof(status) == 'undefined' )
			status = !this.isControl();
		//Обработчики автоубирания окна
		this.setHandler(!status);
		if( status )
		{
			this.pFormC.style.display = 'block';
			this.pForm.email.focus();
		}
		else
			this.pFormC.style.display = 'none';
		return false;
	}
	//Включить/отключить всплывающее окошко
	this.Switch = function(status /*true - вкл., false - откл.*/)
	{
		if( typeof(status) == 'undefined' )
			status = getCookie('toolTip') ? true: false;
		this.pSwitch.className = 'script';
		if( status )
		{
			this.pSwitch.innerHTML = 'Выделите текст и напишите нам';
			delCookie('toolTip', '/');
		}
		else
		{
			this.Hide();
			this.pSwitch.innerHTML = 'Выделите текст и нажмите Ctrl+Enter';
			setCookie('toolTip', 'false', 'Mon, 01-Jan-2035 01:01:23 GMT', '/');
		}
		return false;
	}
	//Отключить/включить обработчики событий
	this.setHandler = function(status)
	{
		document.onmousemove = window.onscroll = status ? eventMouseMove: null;
	}
	//Спрятать окошко и отключить обработчики событий
	this.Hide = function()
	{
		this.pWin.style.display = 'none';
		this.Control(false);
		this.setHandler(false);
	}
	//Показать окошко и включить обработчики событий
	this.Show = function(x, y)
	{
		this.pWin.style.display = 'block';
		var mPage = getPageBrowse();
		mPage.x -= x + this.shiftX + this.pWin.offsetWidth + 5;
		mPage.y -= y + this.shiftY + this.pWin.offsetHeight + 5;
		this.pWin.style.left = mPage.x > 0 ? x + this.shiftX + 'px': x + mPage.x + this.shiftX + 'px';
		this.pWin.style.top = mPage.y > 0 ? y + this.shiftY + 'px': y + mPage.y + this.shiftY + 'px';
		this.setHandler(true);
	}
	//Вышел за пределы допустимого
	this.isOut = function(x, y)
	{
		if( (x < this.pWin.offsetLeft - this.shiftX - this.deltaX) || (x > this.pWin.offsetLeft + this.pWin.offsetWidth + this.deltaX) ||
			(y < this.pWin.offsetTop - this.shiftY - this.deltaY) || (y > this.pWin.offsetTop + this.pWin.offsetHeight + this.deltaY) )
				return true;
		return false;
	}
	//Вышел за пределы окошка
	this.isOutWin = function(x, y)
	{
		if( (x < this.pWin.offsetLeft) || (x > this.pWin.offsetLeft + this.pWin.offsetWidth) ||
			(y < this.pWin.offsetTop) || (y > this.pWin.offsetTop + this.pWin.offsetHeight) )
				return true;
		return false;
	}
	//Получение выделенного текста
	this.getSelect = function()
	{
		this.tSel = String(document.selection ? document.selection.createRange().text : 
						document.getSelection ? document.getSelection():
						window.getSelection ? window.getSelection(): '');
		return this.tSel;
	}
}
pToolTip = new CToolTip();

/************************* Обработчики ********************************************************/
//Перемещение мыши
function eventMouseMove(even)
{
	var mCurs = getMouseOnPage(even);
	if( pToolTip.isOut(mCurs.x, mCurs.y) )
		pToolTip.Hide();
}
//Выделения мышью
function eventMouseUp(even)
{
	if(!even) even = window.event;
	var mCurs = getMouseOnPage(even);
	//Пропускаем, если клики по окошку или отключен показ или выведена форма
	if( pToolTip.isOutWin(mCurs.x, mCurs.y) && getCookie('toolTip') != 'false' && !pToolTip.isControl() )
	{
		//Пропускаем, если в форме
		var e = even.target ? even.target: even.srcElement ? even.srcElement: null;
		pToolTip.tHtml = e.outerHTML; //Сохраняем элемент
		for(var i = 0; i < 20; i++)
			if( e.nodeName == 'FORM' || (e = e.parentNode) == null )
				break;
		//Выделенный текст и не в форме?
		if( pToolTip.getSelect().length && (e == null || e.nodeName != 'FORM') )
			pToolTip.Show(mCurs.x, mCurs.y);
		else
			pToolTip.Hide();
	}
}
//Нажатия клавиш
document.onkeypress = function( even )
{
	if(!even) even = window.event;
	var keyCode = even.which ? even.which: even.keyCode;
	if ( even.ctrlKey && (keyCode == 13 || keyCode == 10) && pToolTip.getSelect().length )
	{
		pToolTip.Show(Math.floor((document.documentElement.clientWidth || document.body.clientWidth)/2), (document.documentElement.scrollTop || document.body.scrollTop) + 100 );
		pToolTip.Switch(true);
		pToolTip.setHandler(false);
	}
}

/************************* toolTipPic *********************************************************/
function CToolTipPic(idPic, srcPic, widthPic, heightPic, urlClick)
{
	this.timerHide = null;
	this.timerShow = null;
	this.maxWidth	= widthPic;							//Ширина большо картинки
	this.maxHeight	= heightPic;						//Высота большой картинки
	this.wCurrent	= 0;								//Текущая ширина
	this.Status		= 0;								//Статус
	this.pImg		= document.getElementById(idPic);	//Указатель на исходную картинку
	this.pTip		= document.createElement('IMG');	//Указатель на большую картинку
	this.pTip.src	= srcPic;							//Большая картинка
	this.pTip.className = 'toolTipPic';
	this.wStep = (this.maxWidth - this.pImg.width)/10;	//Шаг роста/уменьшения
    document.body.insertBefore(this.pTip, document.body.firstChild);	//Добавляем toolTipPic (заплатка от падения IE)
	this.pImgPos = getPosition(this.pImg);				//Получаем координаты картинки
	this.pTip.style.left = this.pImgPos.left+'px';
	this.pTip.style.top = this.pImgPos.top+'px';
	if(urlClick)
	{
		this.pTip.style.cursor = 'pointer';
		this.pTip.onclick = function(){ window.location = urlClick };
	}
	//Обработчик
	this.setEvents = function(pTip)
	{
		pTip.pImg.onmousemove = function(){ pTip.stopShow(); pTip.Show(); pTip.timerShow = setInterval( function(){ pTip.Show() }, 20); };
		pTip.pTip.onmouseout = function(){ pTip.stopHide(); pTip.Hide(); pTip.timerHide = setInterval( function(){ pTip.Hide() }, 20); };
	}
	//Обработчик по клику
	this.setEventsClick = function(pTip)
	{
		pTip.pImg.onclick = function(){ pTip.stopShow(); pTip.Show(); pTip.timerShow = setInterval( function(){ pTip.Show() }, 20); };
		pTip.pTip.onclick = function(){ pTip.stopHide(); pTip.Hide(); pTip.timerHide = setInterval( function(){ pTip.Hide() }, 20); };
	}
	//Останавливаем таймер
	this.stopHide = function()
	{
		if(this.timerHide)
			clearInterval(this.timerHide);
		this.timerHide = null;
	}
	//Останавливаем таймер
	this.stopShow = function()
	{
		if(this.timerShow)
			clearInterval(this.timerShow);
		this.timerShow = null;
	}
	//Скрыть картинку
	this.Hide = function()
	{
		if( this.Status == 1 )
		{ //Вверх
			this.stopShow();
			this.Status = 2;
		}
		if( this.Status == 2 )
		{ //Вниз
			this.wCurrent -= this.wStep;
			if( this.wCurrent <= this.pImg.width )
				this.Status = 0;
			this.Position();
		}
		if( this.Status == 0 )
		{
			this.stopHide();
			this.pTip.style.display = 'none';
		}
	}
	//Показать картинку
	this.Show = function()
	{
		if( this.Status == 0 )
		{
			this.stopHide();
			this.Status = 1;
			this.wCurrent = this.pImg.width;
			this.pImgPos = getPosition(this.pImg);
			this.pTip.style.display = 'block';
		}
		if( this.Status == 1 )
		{
			this.Position();
			this.wCurrent += this.wStep;
			if( this.wCurrent >= this.maxWidth )
			{
				this.wCurrent = this.maxWidth;
				this.Position();
				this.stopShow();
				this.Status = 2;
			}
		}
	}
	this.Position = function()
	{
		this.pTip.width = this.wCurrent;
		this.pTip.height = this.wCurrent * this.maxHeight / this.maxWidth;
		var left = (this.pImgPos.left > Math.ceil( (this.wCurrent - this.pImg.width)/10 ) ? this.pImgPos.left - Math.ceil( (this.wCurrent - this.pImg.width)/10 ): 0);
		var top = (this.pImgPos.top > Math.ceil( (this.wCurrent - this.pImg.width)/10 * this.maxHeight / this.maxWidth ) ? this.pImgPos.top - Math.ceil( (this.wCurrent - this.pImg.width)/10 * this.maxHeight / this.maxWidth ): 0);
		var mPage = getPageBrowse();
		this.pTip.style.left = (left+this.pTip.width > mPage.x-10 ? (mPage.x-this.pTip.width-10 > 0 ? mPage.x-this.pTip.width-10: 10): left) + 'px';
		this.pTip.style.top = (top+this.pTip.height > mPage.y-10 ? (mPage.y-this.pTip.height > 0 ? mPage.y-this.pTip.height-10: 10): top) + 'px';
	}
}

/************************* Tools **********************************************************/
//Получаем координаты курсора мыши на странице
function getMouseOnPage(e)
{
	if(!e) e = window.event;
	var x = e.pageX ? e.pageX: e.clientX ? e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft: 0;
	var y = e.pageY ? e.pageY: e.clientY ? e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop: 0;
	return {'x': x, 'y': y};
}
//Получаем размер экрана браузера
function getScreenBrowse()
{
	var x = window.innerWidth ? window.innerWidth: document.body.offsetWidth;
	var y = window.innerHeight ? window.innerHeight: document.body.offsetHeight;
	return {'x': x, 'y': y};
}
//Получаем смещение экрана браузера
function getPageBrowse()
{
	var x = document.body.scrollLeft + document.body.clientWidth;
	var y = document.body.scrollTop + document.body.clientHeight;
	return {'x': x, 'y': y};
}
//Получаем координаты элемента на странице
function getPosition(elem)
{
	var l = 0;
	var t = 0;
	while(elem)
	{
		l += elem.offsetLeft;
		t += elem.offsetTop;
		elem = elem.offsetParent;
	}
	return {'left':l, 'top':t};
}
//Cookies
function setCookie(name, value, expires, path, domain, secure)
{
	document.cookie = name + '=' + escape(value) +
		((expires) ? '; expires=' + expires : '') +
		((path) ? '; path=' + path : '') +
		((domain) ? '; domain=' + domain : '') +
		((secure) ? '; secure' : '');
}
function getCookie(sName)
{
	var aCrumb;
    if (document.cookie.length > 0)
	{
		var aCookie = document.cookie.split(';');
		for(var i = 0; i < aCookie.length; i++)
			if( (aCrumb = aCookie[i].replace(/^([ ]+)/, '')) && sName == aCrumb.substr(0, sName.length) && (aCrumb[sName.length] == undefined || aCrumb[sName.length] == '=') ) 
				return unescape(aCrumb.substr(sName.length+1));
	}
	return null;
}
function delCookie(name, path, domain)
{
	if ( getCookie(name) )
		setCookie(name, '', ';expires=Thu, 01-Jan-1970 01:01:34 GMT', path, domain);
}

