/**
 *  Div Style Scroller v2.1
 *  2k-Group, NickM (Nickproger)
 * 
 * divStyleScroller()
 *
 * content_id
 * menu_id
 * scrollerBar_id
 * scroller_id
 * scrollerTrackHeight_val
 * scrollerHeight_val		// if Scroller-Height is indicated (for example "30"), then it takes this value. If it not indicated (empty value "" or zero "0"), then height of Scroller will be count automatically.
 *
 *
 * It was used manual for scroll-creating from here: http://www.noinimod.ru/52/
 * 
 * "Example of use" is placed in the end of this file.
 */


divStyleScroller = function (content_id, menu_id, scrollerBar_id, scroller_id, scrollerTrackHeight_val, scrollerHeight_val)
{ 
	var content_element = document.getElementById(content_id);

	this.get = function (id) {
		return document.getElementById(id);
	}

	this.scroller = this.get(scroller_id);
	this.scrollerBar = this.get(scrollerBar_id);
	this.menu = this.get(menu_id);

	this.content = this.get(content_id);
	this.scrollerTrackHeight = scrollerTrackHeight_val;
	this.objectHeight = this.content.offsetHeight; 
	this.objectTrackHeight = this.menu.offsetHeight; 

	var scrollerHeightAutoDetected = Math.round( (this.objectHeight * this.scrollerTrackHeight) / this.objectTrackHeight );

	this.scrollerHeight = (scrollerHeight_val!='' && scrollerHeight_val!=0) ? scrollerHeight_val : scrollerHeightAutoDetected;

	// If Scroller-Height more ScrollBar-Height then  disable Scroll at all
	this.scrollEnabled = (scrollerHeightAutoDetected < this.scrollerTrackHeight) ? true : false;
	var isScrollEnabled = this.scrollEnabled;
	this.scrollerBar.style.display = this.scrollEnabled ? "block" : "none";

	try
	{
		this.scroller.style.height = this.scrollerHeight + "px";
	}
	catch(e)
	{
		this.scroller.style.height = "0px";
	}
	// For one pixel of scroll-moving compare delta value
	this.delta = this.scrollEnabled ? (this.objectTrackHeight - this.objectHeight) / (this.scrollerTrackHeight - this.scrollerHeight) : 0;
	this.step =  10/this.delta;
	// Moving or Draging indicator
	this.canDrag = false;
	// start scroller shift
	this.shift_y = 0;


	this.jump = function (event) {
		if (!event) {
			// For IE.
			event = window.event;
		}

		// если курсор находится на кнопке для перетаскивания, то не совершаем прижок

		if (event.target != this.scroller) {
			var clickY = event.layerY ? event.layerY : event.offsetY;
			var currentPosition = parseInt(this.scroller.style.marginTop); 
			// вычисляем направление прыжка
			var i = (clickY > currentPosition) ? 1 : -1;
			var newPosition = 2*i*this.step + currentPosition; 
			this.setPosition(newPosition);
			this.fixForBrowsers(event);
       		}

		return false;
	}

	this.drag = function (event) {

		if (!event) {
			// Всем известно, что в Mozilla event передается как параметр
			// А в IE его можно получить вот так:
			event = window.event;
		}

		// Отметим, что мы захватили ползунок.
		// Теперь при сдвиге мыши, ползунок должен сдвинуться вместе с ней
		this.canDrag = true;

		// А так же запомним начальный сдвиг
		this.shift_y = event.clientY - parseInt(this.scroller.style.marginTop);
		return false;
	}

	this.move = function (event) {
		if (!event) {
			event = window.event;
		}

		// Здесь мы как раз и проверяем:
		// Сдвигать ли нам ползунок вслед за мышью, или оставить его неподвижным.
		
		if (this.canDrag) {
			this.setPosition(event.clientY - this.shift_y);
		}
		return false;
	}

	this.drop = function () {
		// Освобождаем ползунок
		this.canDrag = false; 
	}

	this.setPosition = function (newPosition) {
		// Проверим не выйдет ли наш ползунок за границы полосы прокрутки
		// Заметим что предельной точкой справа является разность ширины полосы прокрутки и ширины ползунка
		// Ведь мы устанавливаем позицию его левой границы

		if ( (newPosition <= this.scrollerTrackHeight - this.scrollerHeight) && (newPosition >= 0) ) {
			this.scroller.style.marginTop = newPosition + "px";
		} else if (newPosition > this.scrollerTrackHeight - this.scrollerHeight) {
			this.scroller.style.marginTop = this.scrollerTrackHeight - this.scrollerHeight + "px";
		} else {
			this.scroller.style.marginTop = 0 + "px";
		}
		// Вслед за ползунком передвинем меню:
		this.menu.style.marginTop = Math.round( parseInt(this.scroller.style.marginTop) * this.delta * (-1) ) + "px";
		return false;
	}

	this.blockEvent = function (event) {
		if (!event) {
			event = window.event;
		}

		if(event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}

		if(event.preventDefault) {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}
	}

	this.wheel = function (event) {
		// Переменная, в которой будем хранить сдвиг
		var wheelDelta = 0;
 
		// Шаг меню при прокрутке

		if (!event) {
			event = window.event;
		}

		if (event.wheelDelta) {
			// В IE и Opera при сдвиге колеса на один шаг event.wheelDelta принимает значение 120
			// Значения сдвига в этих двух браузерах совпадают по знаку.
			wheelDelta = -event.wheelDelta/120;
		} else if (event.detail) {
			// В Mozilla, значение wheelDelta отличается по знаку от значения в IE.
			// Сдвиг колеса на один шаг соответствует значению 3 параметра event.detail 
			wheelDelta = event.detail/3;
		}

		// При скроллинге вверх wheelDelta > 0
		// При скролинге вниз - wheelDelta < 0

		if (wheelDelta) {
			var currentPosition = parseInt(this.scroller.style.marginTop); 
			var newPosition = wheelDelta*this.step + currentPosition;
			this.setPosition(newPosition); 
		}

		// Убиваем событие (чтобы страница не скроллилась)


		if (event.preventDefault) {
			event.preventDefault();
		}

		event.returnValue = false;
		this.blockEvent(event);

	}

	this.fixForBrowsers = function(event) {
		if (!event) {
			// For IE.
			event = window.event;
		}

		if(event.stopPropagation) {
			event.stopPropagation();
		} else {
			event.cancelBubble = true;
		}

		if(event.preventDefault) {
			event.preventDefault();
		} else {
			event.returnValue = false;
		}
	}
	var sfunc = function () {};

	if (this.scrollEnabled == true) {
		// Init events
		var this_scroll = this;
		this.scrollerBar.onmousedown	= function (event) {this_scroll.drag(event)};
		this.scrollerBar.onmousemove	= function (event) {this_scroll.move(event)};
		this.scrollerBar.onmouseup	= function (event) {this_scroll.drop(event)};
		this.scrollerBar.onclick	= function (event) {this_scroll.jump(event)};
		// For Mozilla
		if (this.content.addEventListener) 
		{
			this.content.addEventListener('DOMMouseScroll', sfunc = function (event){this_scroll.wheel(event)}, false);
		}
		//For all another Browsers
		this.content.onmousewheel = function (event){this_scroll.wheel(event)};
	}
	else
	{
		if (this.content.removeEventListener) 
		{       
			this.content.removeEventListener('DOMMouseScroll', sfunc, false);
		}
		this.content.onmousewheel = null;
	}
}


/*////// Example of use ////////

<div id="content_id">

	<div style="margin-top:0px;" id="menu_id">
	.....
	</div>

	<div id="scrollerBar_id" style="display:none;">        
	        <div id="scroller_id" style="margin-top: 0px;"></div>
	</div>

</div>
<script text="text/javascript" src="js/div_style_scroller.js"></script>
<script text="text/javascript">
	var vertical_divStyleScroller = new divStyleScroller('content_id', 'menu_id', 'scrollerBar_id', scroller_id'', 300, 30);
</script>

//////////////////////////////*/