/*
Объект "Scroller" создает полосу прокрутки с помощью блоковых элементов. Он имеет 
пять входных параметров
 1. "controlDiv" - элемет являющийся бегунком полосы прокрутки;
 2. "contentDiv" - элемент в котором находится содержимое которое должно прокручиватся;
 3. "wrapDiv" - элемент являющийся контейнером для "contentDiv";
 4. "scrollTopHandler" - элемент являющийся верхней кнопкой полосы прокрутки;
 5. "scrollBottomHandler" - элемент являющийся нижней кнопкой полосы прокрутки;

Для коректной работы полосы прокрутки в элементы "controlDiv", "scrollTopHandler" и "scrollBottomHandler"
добавлены по одному дочернему элементу "А", которому присвоин индефикатор "id" равный
индефикатору "id" родительского элемента в конец которого добавлено "Button". Это сделана
для того чтобы при перетаскивании ползунка прокрутки и выхода курсора за его границы не
происходило выделения элементов полосы прокрутки и контента.

При создании экземпляра объекта "Scroller" происходит инициализация определенных свойств
для произвидения с ними определенных вычислений и определение обработчиков событий для
элементов полосы прокрутки.
*/
var scroll1;

function Scroller(mainScrollDiv, controlDiv,contentDiv,wrapDiv,scrollTopHandler,scrollBottomHandler, toTop)
{
	if (toTop==undefined)
		toTop = false;
	//Эта функция возвращает значение стиля FLOAT;
	this.getFloatPropertyValue=function(obj)
	{
		return obj.currentStyle?obj.currentStyle.styleFloat:window.getComputedStyle(obj, null).getPropertyValue("float");
	}

	//Эта функция возвращает значение стиля POSITION;
	this.getPositionPropertyValue=function(obj1)
	{
		return obj1.currentStyle ? obj1.currentStyle.position : window.getComputedStyle(obj1, null).getPropertyValue("position");
	}

	//Возвращает смещение елемента "element";
	this.getOffset=function(element, offsetName)
	{
		var result = 0;
		while (element != null)
		{
			result += eval("element." + offsetName);
			element = element.offsetParent;
			if (element != null && (this.getFloatPropertyValue(element) != "none" || this.getPositionPropertyValue(element) == "absolute" || this.getPositionPropertyValue(element) == "relative"))
			{
			break;
			}
		}
		return result;
	}

	//Свойство для инициализации таймера;
	this.updown;
	this.IE=     !!(window.attachEvent && !window.opera);
	this.NC = (document.layers); // Netscape
	this.Opera=  !!window.opera;
	this.WebKit= navigator.userAgent.indexOf('AppleWebKit/') > -1;
	this.Gecko=  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1;
	this.MobileSafari= !!navigator.userAgent.match(/Apple.*Mobile.*Safari/);
	this.mozz = !this.IE;
	var MIN_controlVert_HEIGHT=30;
	var mainObject=this;
	this.prevY;

	//Возвращаем бегунок полосы прокрутки;
	this.controlVert = document.getElementById(controlDiv);

	//Возвращаем элемент с прокручивающимся контентом;
	this.contentVert = document.getElementById(contentDiv);

	//Возвращаем родительский элемент для элемента с контентам;
	this.wrapDivVert = document.getElementById(wrapDiv);
	
	//Возвращаем высоту родительского элемента;
	this.wrapDivHeight = this.wrapDivVert.offsetHeight;

	//Возвращаем высоту элемента с контентом;
	this.contentHeight = this.contentVert.offsetHeight;
	
	/*Возвращаем "textFactorVert" с помощью деления высоты родительского элемента на
	 высоту элемента с контентом. Если высота элемента с контентом больще высоты родительского
	 элемента то получается значение меньще 1. В противном случае получается 1 или больше
	 С помощью этого мы определяем нужна ли прокрутка для элемента с контентом.*/
	// если не требуеться прокрутка скрол не отображаеться
	this.textFactorVert = this.wrapDivHeight / this.contentHeight;
	if (this.textFactorVert > 1) {
		this.textFactorVert = 1;
		document.getElementById(mainScrollDiv).style.display='none';
	} else {
		document.getElementById(mainScrollDiv).style.display='inline';
	}
	/*if (!this.IE && !this.Opera){
		document.getElementById('mainScroll').style.display='none';
		this.wrapDivVert.style.overflow = "auto";
	}*/
	
	
	/*Возвращаем высоту верхней кнопки полосы прокрутки и прибавляем к ней 1.
	 Это будет служить верхней границей для бегунка полосы прокрутки.*/
	this.scrollBarTop = document.getElementById(scrollTopHandler).offsetHeight + 1;
	/*Возвращаем границу верхнего смещения для нижней кнопки полосы прокрутки и 
	 отнимаем от нее 2 (если браузер клиента "Mozilla") или 1 в противном случае.
	 Это будет служить нижней границей для бегунка полосы прокрутки.*/
	this.scrollBarDown = (this.mozz) ? (this.getOffset(document.getElementById(scrollBottomHandler), "offsetTop") - 2) : (this.getOffset(document.getElementById(scrollBottomHandler), "offsetTop") - 1);

	/*Возвращаем высоту свободной области между верхней и нижней границами.
	 Это будет служить пространством для движения бегунка полосы прокрутки.*/
	this.scrollBarHeight = this.scrollBarDown - this.scrollBarTop;

	/*Устанавливаем левую кординату бегунка полосы прокрутки равной левому смещению
	 верхней кнопки полосы прокрутки.*/
	this.controlVert.style.left = this.getOffset(document.getElementById(scrollTopHandler), "offsetLeft")  + "px";

	//Возвращаем высоту бегунка полосы прокрутки;
	this.controlVertHeight = this.controlVert.offsetHeight;
	
	//Устанавливаем верхнию кординату бегунка полосы прокрутки равной "scrollBarTop";
	if (toTop)
		this.controlVert.style.top = this.scrollBarTop + "px";
	else
		this.controlVert.style.top = (Math.ceil(this.contentVert.offsetTop / (this.wrapDivHeight - this.contentHeight) * (this.scrollBarDown - this.scrollBarTop - this.controlVertHeight) + this.scrollBarTop)) + "px";
	
	

	//Устанавливаем высоту бегунка полосы прокрутки;
	//this.controlVert.style.height = this.controlVertHeight + "px";

	
	this.scrollBarBlank = this.scrollBarWidth * (1 - this.textFactorVert);

	//Возвращаем оставшуюся свободную область для движения бегунка полосы прокрутки;
	this.scrollBarBlankVert = Math.ceil(this.scrollBarDown - this.controlVertHeight);
	
	this.controlVert.style.visibility = "visible";

	//Устанавливаем обработчики событий для кнопок полосы прокрутки;
	this.scrollButtonSlider=document.getElementById(controlDiv+"Button");
	this.scrollButtonSlider.onmousedown=function() { mainObject.dragText(); return false; }
	this.scrollButtonSlider.onmouseup=function() { mainObject.stopScrolling(); return false; }
	this.scrollButtonSlider.ondragstart=function() { return false; }
	this.scrollButtonSlider.onclick=function() { return false; }

	this.scrollButtonDown=document.getElementById(scrollBottomHandler+"Button");
	this.scrollButtonDown.onmousedown=function() { mainObject.moveDown(1); return false; }
	this.scrollButtonDown.onmouseup=function() { mainObject.stopScrolling(); return false; }
	this.scrollButtonDown.onclick=function() { return false; }
	this.scrollButtonDown.onmouseout=function() { mainObject.stopScrolling(); }
	this.ScrollButtonUp=document.getElementById(scrollTopHandler+"Button");
	this.ScrollButtonUp.onmousedown=function() { mainObject.moveUp(1); return false; }
	this.ScrollButtonUp.onmouseup=function() { mainObject.stopScrolling(); return false; }
	this.ScrollButtonUp.onclick=function() { return false; }
	this.ScrollButtonUp.onmouseout=function() { mainObject.stopScrolling(); }

	this.wrapDivVert.onmouseover=function() { document.onmousewheel=function() { mainObject.doWheel(); } }
	this.wrapDivVert.onmouseout=function() { document.onmousewheel=null; }

}

/*Эта функция инициализирует переменные для прокрутки контента вниз изапускает таймер,
 который вызывает функцию прокрутки контента.*/
Scroller.prototype.moveUp=function(speed)
{
	if (this.textFactorVert == 1) return;
	if (this.mozz) speed *= 2;
	mainObj=this;
	var factor=(speed/this.textFactorVert);
	func=this.doMoveVert;
	this.updown = window.setInterval("func("+factor+")", 10);
}
/*Эта функция инициализирует переменные для прокрутки контента вверх изапускает таймер,
 который вызывает функцию прокрутки контента.*/
Scroller.prototype.moveDown=function(speed)
{
	if (this.textFactorVert == 1) return;
	if (this.mozz) speed *= 2;
	mainObj=this;
	var factor=-(speed/this.textFactorVert);
	func=this.doMoveVert;
	this.updown = window.setInterval("func("+factor+")", 10);
}
/*Эта функция осуществляет прокрутку контента по таймеру. Если переменная "factor" имеет
 положительное значение то прокрутка контента осущесвляется вниз, если отрицательное - вветх.*/
Scroller.prototype.doMoveVert=function(factor)
{
	//Нижняя граница прокрутки контента
	maxTextPosition = mainObj.wrapDivHeight - mainObj.contentHeight;
	//Проверяем не вышел ли за дпустимые границы элемент с контентом;
	if (((mainObj.contentVert.offsetTop >= 0) && (factor > 0)) || ((mainObj.contentVert.offsetTop <= maxTextPosition) && (factor < 0)))
	{
		mainObj.stopScrolling();
		return;
	}
	//Возвращаем новую позицию элемента;
	var newPosition = mainObj.contentVert.offsetTop + factor;
	if (newPosition > 0) newPosition = 0;
	if (newPosition < maxTextPosition) newPosition = maxTextPosition;
	
	//Присваеваем новую позицию элементу с контентом;
	mainObj.contentVert.style.top = newPosition + "px";

	//Присваеваем новую позицию для бегунка полосы прокрутки.
	mainObj.controlVert.style.top = (Math.ceil(mainObj.contentVert.offsetTop / maxTextPosition * (mainObj.scrollBarDown - mainObj.scrollBarTop - mainObj.controlVertHeight) + mainObj.scrollBarTop)) + "px";
}
//Эта функция осуществляет инициализацию для прокрутки контента при нажатии на бегунок полосы прокрутки;
Scroller.prototype.dragText=function()
{
	if (this.textFactorVert == 1) return;
	var mainObject=this;
	this.prevY = false;
	document.onmousemove = function(e) { mainObject.dragItVertical(e); }
	document.onmouseup = function() { mainObject.dropIt(); }
}
Scroller.prototype.dragItVertical=function(e)
{
	//Возвращаем y-кординату;
	y = (document.all) ? event.clientY : e.pageY;
	if (document.all) y += document.body.scrollTop;
	if (this.prevY == false)
	{
		this.prevY = y;
		return;
	}
	if ((this.controlVert.offsetTop >= this.scrollBarTop) && (this.controlVert.offsetTop <= this.scrollBarBlankVert))
	{
		if ((y < this.prevY) && ((this.controlVert.offsetTop + (y - this.prevY)) < this.scrollBarTop))
			this.controlVert.style.top = this.scrollBarTop + "px";
		else if ((y > this.prevY) && ((this.controlVert.offsetTop + (y - this.prevY)) > this.scrollBarBlankVert))
			this.controlVert.style.top = this.scrollBarBlankVert + "px";
		else
			this.controlVert.style.top = (this.controlVert.offsetTop + (y - this.prevY)) + "px";
	}
	if (this.controlVert.offsetTop < this.scrollBarTop) this.controlVert.style.top = this.scrollBarTop + "px";
	if (this.controlVert.offsetTop > this.scrollBarBlankVert) this.controlVert.style.top = this.scrollBarBlank + "px";
	this.contentVert.style.top = ((this.controlVert.offsetTop - this.scrollBarTop) / (this.scrollBarDown - this.scrollBarTop - this.controlVertHeight) * -(this.contentHeight - this.wrapDivHeight)) + "px";
	this.prevY = y;
}
Scroller.prototype.dropIt=function()
{
	document.onmousemove = null;
}
Scroller.prototype.stopScrolling=function()
{
	window.clearInterval(this.updown);
}
Scroller.prototype.doWheel=function(event)
{
	mainObj=this;
	if (!event) /* For IE. */
                event = window.event;
	if (event && (event.wheelDelta))
	{
		//event.stop();
		this.doMoveVert(event.wheelDelta);
	} else if (this.mozz) {
		event.stop();
		this.doMoveVert((event.detail)*-10);
	}
	return false;
}

function StartScroller(toTop){
	if (document.getElementById('textWrap'))
	{
		scroll1 = null;
		scroll1 = undefined;
		scroll1=new Scroller('mainScroll', 'textScroll','textContent','textWrap', 'textScrollUp', 'textScrollDown', toTop);
		if (toTop) {
			scroll1.contentVert.style.top = "0px";
		}
		if (scroll1.IE) {
			document.getElementById('textWrap').onMouseWheel=scroll1.doWheel;
		}
	}
}
window.onload=function()
{
		StartScroller(1);
		if (document.getElementById('textWrap')){
			if ( !(!!(window.attachEvent && !window.opera)) ){
				document.getElementById('textWrap').addEventListener('DOMMouseScroll', scroll, false);
		
			} 
			//new ScrollBox('textWrap');
		}
}

function scroll(e){
	scroll1.doWheel(e);
}

function GenerateScroller(toTop, mainScroll, textWrap, textScroll, textContent, textScrollUp, textScrollDown){
	if (document.getElementById(textWrap))
	{
		scroll2 = null;
		scroll2 = undefined;
		scroll2=new Scroller(mainScroll, textScroll, textContent, textWrap, textScrollUp, textScrollDown, toTop);
		if (toTop) {
			scroll2.contentVert.style.top = "0px";
		}
		if (scroll2.IE) {
			document.onMouseWheel=scroll2.doWheel;
		}
	}
	//console.log(scroll2);
}

