/*
* Скрипт реализующий горизонтальный скроллер бар
* обрататывает события перемещения скроллера мышью,
* клик по линнии скролла
* прокрутка колесом мыши.
* Автоподгон ширины скроллера
*/

Scroll = function (scroller, scroller_bar, menu, widthAll)
{
    this.canDrag = false;
    this.prepared = false;

    this.shift_x;
    this.delta;

    this.scroller = scroller;
    this.scrollerBar = scroller_bar;
    this.menu = menu;

    this.scrollerStartShift;
    this.menuStartShift;

    this.scrollerTrackWidth = widthAll;
    this.menuTrackWidth;

    this.scrollerWidth;
    this.menuWidth = widthAll;

    this.step;

    this.dontmove = false;

    this.a = false;

    this.prepare = function()
    {
        if(get(this.scroller) && get(this.menu))
        {
            this.scroller = get(this.scroller);
            this.scrollerBar = get(this.scroller_bar);
            this.menu = get(this.menu);
            
            this.scrollerStartShift = parseInt(this.scroller.style.left);
			if (isNaN(this.scrollerStartShift)) {this.scroller.style.left=0;this.scrollerStartShift=0;}
            this.menuStartShift = parseInt(this.menu.style.marginLeft);
			if (isNaN(this.menuStartShift)) this.menuStartShift=0;
            
            this.menuTrackWidth = this.menu.offsetWidth + this.menuStartShift;
            
            this.scrollerWidth = Math.round( (this.menuWidth * this.scrollerTrackWidth) / this.menuTrackWidth );
            
            // 8 px - ширина стрелки => минимальная ширина скроллера 16px        
            this.scrollerWidth = (this.scrollerWidth < 16) ?  16 : this.scrollerWidth;
            
            // максимальная ширина скроллера - ширина трэка
            this.scrollerWidth = (this.scrollerWidth > this.scrollerTrackWidth) ?  this.scrollerTrackWidth : this.scrollerWidth;
            
            // устанавливаем ширину скроллера 
            this.scroller.style.paddingRight = this.scrollerWidth - 8 + "px";
            
            // теперь принимаем за скроллер точку (его левую границу), все расчеты будем производить относительно нее
            // задаем ширину трэка скроллера и меню
            this.scrollerTrackWidth -= this.scrollerWidth;
            this.menuTrackWidth -= this.menuWidth;
            
            // рассчитываем коэффициэнт
			this.delta=0;
            this.delta = (parseInt(this.menuTrackWidth)/parseInt(this.scrollerTrackWidth));

            this.prepared = true;
        }
        return false;
    }

    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;
    }

    this.setStep = function()
    {
        //step = Math.round(scrollerWidth / 3 * 2);
//		alert(this.menuTrackWidth);
        this.step = Math.round(this.menu.getElementsByTagName("td")['0'].offsetWidth * this.scrollerTrackWidth / this.menuTrackWidth / 2);    
    }

    this.setPosition = function(newPosition)
    {
	
        if(newPosition <= this.scrollerTrackWidth + this.scrollerStartShift && newPosition >= this.scrollerStartShift)
        {
            this.scroller.style.left = newPosition + "px";
        }
        else
        {
            if(newPosition >= this.scrollerTrackWidth + this.scrollerStartShift)
            {        
                this.scroller.style.left = this.scrollerTrackWidth + this.scrollerStartShift + "px";
            }
            if(newPosition < this.scrollerStartShift)
            {
                this.scroller.style.left = this.scrollerStartShift + "px";
            }
        }
        this.menu.style.marginLeft = Math.round( (parseInt(this.scroller.style.left) - this.scrollerStartShift) * this.delta * (-1) ) + this.menuStartShift + "px";
//		alert(this.step);
//		alert(this.menu.style.marginLeft);
		if (this.step==17)
		{
			this.menu.style.marginLeft="-"+Math.round(parseInt(this.scroller.style.left)/34*160) + "px";
		}
//		alert(this.menu.style.marginLeft);
        return false;
    }

    this.drag = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared)
        {
            this.canDrag = true;
            this.shift_x = event.clientX - parseInt(this.scroller.style.left);
            this.fixForBrowsers(event);
        }    
        return false;
    }

    this.movescroller_ = function(event,i)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared && !this.dontmove)
        {
            this.setStep();
            var currentPosition = parseInt(this.scroller.style.left);               
            var newPosition = 2*i*this.step + parseInt(this.scroller.style.left); 
//			alert(newPosition);
            this.setPosition(newPosition);
            this.fixForBrowsers(event);
        }
        else
        {
            this.dontmove = false;
        }
        return false;
    }

    this.movescroller = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared && !this.dontmove)
        {
            this.setStep();
            var clickX = event.layerX ? event.layerX : event.offsetX;
            var currentPosition = parseInt(this.scroller.style.left);               
            var i = (clickX > currentPosition) ? 1 : -1;


            var newPosition = 2*i*this.step + parseInt(this.scroller.style.left); 
            this.setPosition(newPosition);
            this.fixForBrowsers(event);
        }
        else
        {
            this.dontmove = false;
        }
        return false;
    }

    this.move = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared && this.canDrag)
        {
            this.setPosition(event.clientX-this.shift_x);
            this.fixForBrowsers(event);
        }
        return false;
    }

    this.drop = function()
    {
        this.canDrag=false; 
    }
    
    this.scrollerClickHandler = function()
    {
        this.dontmove=true;    
    }    

    this.handle = function(delta, event) 
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        var i = (delta < 0) ? 1 : -1;
        this.setStep()
        var currentPosition = parseInt(this.scroller.style.left);               
        var newPosition = i*this.step + currentPosition; 
        this.setPosition(newPosition);        
        this.fixForBrowsers(event);        
    }

    this.cancelWheelAction = function(event)
    {
        /*
        Отменяем действие колеса
        */
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (event.preventDefault)
        {
            event.preventDefault();
        }
        event.returnValue = false;
    }

    this.wheel = function(event)
    {
        var delta = 0;
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (event.wheelDelta) 
        {
            // IE/Opera.
            delta = event.wheelDelta/120;
            
            // В Opera 9, значение delta не отличается по знаку от значения в IE.
            if (window.opera)
            {
                delta = delta;
            }
        } 
        else if (event.detail) 
        {
            /* 
            Заточка под Mozilla
            В Mozilla, значение delta отличается по знаку от значения в IE.
            Обычно, delta умножается на 3.
            */    
            delta = -event.detail/3;
        }
        /*
        Если delta отлична от 0 - юзаем ее
        Если скроллить вверх, то delta > 0
        Если скролить вниз - delta < 0
        */
        if (delta)
        {
            this.handle(delta, event);
            this.cancelWheelAction(event);
            this.fixForBrowsers(event);
            return false;
        }
    }
}

VerticalScroll = function (scroller, scroller_bar, menu)
{
    this.canDrag = false;
    this.prepared = false;

    this.shift_y;
    this.delta;

    this.scroller = scroller;
    this.scrollerBar = scroller_bar;
    this.menu = menu;

    this.scrollerStartShift;
	if (isNaN(this.scrollerStartShift)) {this.scrollerStartShift=0;}
    this.menuStartShift;
	if (isNaN(this.menuStartShift)) this.menuStartShift=0;	

    this.scrollerTrackWidth = 190;
    this.menuTrackWidth;

    this.scrollerWidth;
    this.menuWidth = 190;

    this.step;

    this.dontmove = false;

    this.a = false;

    this.prepare = function()
    {
        if(get(this.scroller) && get(this.menu))
        {
            this.scroller = get(this.scroller);
            this.scrollerBar = get(this.scroller_bar);
            this.menu = get(this.menu);
            
            this.scrollerStartShift = parseInt(this.scroller.style.top);
            this.menuStartShift = parseInt(this.menu.style.marginTop);
            
            this.menuTrackWidth = this.menu.offsetHeight + this.menuStartShift;
            
            this.scrollerWidth = Math.round( (this.menuWidth * this.scrollerTrackWidth) / this.menuTrackWidth );
            
            // 8 px - ширина стрелки => минимальная ширина скроллера 16px        
            this.scrollerWidth = (this.scrollerWidth < 16) ?  16 : this.scrollerWidth;
            
            // максимальная ширина скроллера - ширина трэка
            this.scrollerWidth = (this.scrollerWidth > this.scrollerTrackWidth) ?  this.scrollerTrackWidth : this.scrollerWidth;
            
            // устанавливаем ширину скроллера 
            this.scroller.style.paddingBottom = this.scrollerWidth - 18	 + "px";
            
            // теперь принимаем за скроллер точку (его левую границу), все расчеты будем производить относительно нее
            // задаем ширину трэка скроллера и меню
            this.scrollerTrackWidth -= this.scrollerWidth;
            this.menuTrackWidth -= this.menuWidth;
            
            // рассчитываем коэффициэнт
			this.delta=0;
     		this.delta = (parseInt(this.menuTrackWidth)/parseInt(this.scrollerTrackWidth));

            this.prepared = true;
        }
        return false;
    }

    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();
        event.returnValue = false;
    }

    this.setStep = function()
    {
        //this.step = Math.round(this.scrollerWidth / 3 * 2);
        this.step = Math.round(this.menu.getElementsByTagName("td")['0'].offsetHeight * this.scrollerTrackWidth / this.menuTrackWidth);    
    }

    this.setPosition = function(newPosition)
    {
        if(newPosition <= this.scrollerTrackWidth + this.scrollerStartShift && newPosition >= this.scrollerStartShift)
        {
            this.scroller.style.top = newPosition + "px";
        }
        else
        {
            if(newPosition >= this.scrollerTrackWidth + this.scrollerStartShift)
            {        
                this.scroller.style.top = this.scrollerTrackWidth + this.scrollerStartShift + "px";
            }
            if(newPosition <= this.scrollerStartShift)
            {
                this.scroller.style.top = this.scrollerStartShift + "px";
            }
        }
		
        this.menu.style.marginTop = Math.round( (parseInt(this.scroller.style.top) - this.scrollerStartShift) * this.delta * (-1) ) + this.menuStartShift + "px";
		
        return false;
    }

    this.drag = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared)
        {
            this.canDrag = true;
            this.shift_y = event.clientY - parseInt(this.scroller.style.top);
            this.fixForBrowsers(event);
        }    
        return false;
    }

    this.movescroller = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared && !this.dontmove)
        {
            this.setStep();
            var clickY = event.layerY ? event.layerY : event.offsetY;
            var currentPosition = parseInt(this.scroller.style.top);               
            var i = (clickY > currentPosition) ? 1 : -1;
            var newPosition = 2*i*this.step + parseInt(this.scroller.style.top); 
            this.setPosition(newPosition);
            this.fixForBrowsers(event);
        }
        else
        {
            this.dontmove = false;
        }
        return false;
    }

    this.move = function(event)
    {
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (this.prepared && this.canDrag)
        {
            this.setPosition(event.clientY-this.shift_y);
            this.fixForBrowsers(event);
        }
        return false;
    }

    this.drop = function()
    {
        this.canDrag=false; 
    }
    
    this.scrollerClickHandler = function()
    {
        this.dontmove=true;    
    }    

    this.handle = function(delta, event) 
    {        
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        var i = (delta < 0) ? 1 : -1;
        this.setStep()
        var currentPosition = parseInt(this.scroller.style.top);               
        var newPosition = i*this.step + currentPosition; 
        this.setPosition(newPosition);        
        this.fixForBrowsers(event);        
    }

    this.cancelWheelAction = function(event)
    {
        /*
        Отменяем действие колеса
        */
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (event.preventDefault)
        {
            event.preventDefault();
        }
        event.returnValue = false;
    }

    this.wheel = function(event)
    {
        var delta = 0;
        if (!event)
        {
            // For IE.
            event = window.event;
        }
        if (event.wheelDelta) 
        {
            // IE и Safari значения delta всегда строго 120, вне зависимости от настроек пользователя.
            //alert(event.wheelDelta);
            delta = event.wheelDelta/120;
            
            // В Opera 9, значение delta равна 40*количество строк установленных пользователем в настройках
            // Не отличается по знаку от IE
            if (window.opera)
            {
                delta = event.wheelDelta/40;
            }
        } 
        else if (event.detail) 
        {
            /* 
            Заточка под Mozilla
            В Mozilla, значение delta отличается по знаку от значения в IE.
            по модулю delta строго совпадает со значением в пользовательких настройках
            */    
            //alert(-event.detail);
            delta = -event.detail;
        }
        /*
        Если delta отлична от 0 - юзаем ее
        Если скроллить вверх, то delta > 0
        Если скролить вниз - delta < 0
        */
        if (delta)
        {
            this.handle(delta, event);
            //this.cancelWheelAction(event);
            this.fixForBrowsers(event);
            return false;
        }
    }
}



function get(id)
{
    return document.getElementById(id);
}
function handleOnMouseUp(event)
{
    if (first) first.drop(event);
    if (second) second.drop(event);
    if (second3) second3.drop(event);
    if (second4) second4.drop(event);
    if (second5) second5.drop(event);
    if (vertical) vertical.drop(event);	
    if (vertical2) vertical2.drop(event);	
}
function handleOnMouseMove(event)
{
    if (first) first.move(event);
    if (second) second.move(event);
    if (second3) second3.move(event);
    if (second4) second4.move(event);
    if (second5) second5.move(event);
    if (vertical) vertical.move(event);		
    if (vertical2) vertical2.move(event);		
}

// first
function handleOnClickBarFirst(event) 
{
    if (first) first.movescroller(event);
}
function handleOnClickBarFirst_next(event) 
{
    first.movescroller_(event,1);
}
function handleOnClickBarFirst_prev(event) 
{
   if (first) first.movescroller_(event,-1);
}
function handleOnMouseDownFirst(event)
{
    if (first) first.drag(event);
}
function handleOnClickFirst(event) 
{
   if (first) first.scrollerClickHandler(event);
}
function handleOnMouseWheelFirst(event)
{
    if (first) first.wheel(event);
}

var first;

// second
function handleOnClickBarsecond(event) 
{
    if (second) second.movescroller(event);
}
function handleOnClickBarsecond_next(event) 
{
    if (second) second.movescroller_(event,1);
}
function handleOnClickBarsecond_prev(event) 
{
    if (second) second.movescroller_(event,-1);
}
function handleOnMouseDownsecond(event)
{
    if (second) second.drag(event);
}
function handleOnClicksecond(event) 
{
    if (second) second.scrollerClickHandler(event);
}
function handleOnMouseWheelsecond(event)
{
    if (second) second.wheel(event);
}

var second;

// second3
function handleOnClickBarsecond3(event) 
{
    if (second3) second3.movescroller(event);
}
function handleOnClickBarsecond3_next(event) 
{
    if (second3) second3.movescroller_(event,1);
}
function handleOnClickBarsecond3_prev(event) 
{
    if (second3) second3.movescroller_(event,-1);
}
function handleOnMouseDownsecond3(event)
{
    if (second3) second3.drag(event);
}
function handleOnClicksecond3(event) 
{
    if (second3) second3.scrollerClickHandler(event);
}
function handleOnMouseWheelsecond3(event)
{
    if (second3) second3.wheel(event);
}

var second3;

// second4
function handleOnClickBarsecond4(event) 
{
    if (second4) second4.movescroller(event);
}
function handleOnClickBarsecond4_next(event) 
{
    if (second4) second4.movescroller_(event,1);
}
function handleOnClickBarsecond4_prev(event) 
{
    if (second4) second4.movescroller_(event,-1);
}
function handleOnMouseDownsecond4(event)
{
    if (second4) second4.drag(event);
}
function handleOnClicksecond4(event) 
{
    if (second4) second4.scrollerClickHandler(event);
}
function handleOnMouseWheelsecond4(event)
{
    if (second4) second4.wheel(event);
}

var second4;

// second5
function handleOnClickBarsecond5(event) 
{
    if (second5) second5.movescroller(event);
}
function handleOnClickBarsecond_next5(event) 
{
    if (second5) second5.movescroller_(event,1);
}
function handleOnClickBarsecond_prev5(event) 
{
    if (second5) second5.movescroller_(event,-1);
}
function handleOnMouseDownsecond5(event)
{
    if (second5) second5.drag(event);
}
function handleOnClicksecond5(event) 
{
    if (second5) second5.scrollerClickHandler(event);
}
function handleOnMouseWheelsecond5(event)
{
    if (second5) second5.wheel(event);
}

var second5;

// vertical
function handleOnClickBarVertical(event) 
{
    vertical.movescroller(event);
}
function handleOnMouseDownVertical(event)
{
    vertical.drag(event);
}
function handleOnClickVertical(event) 
{
    vertical.scrollerClickHandler(event);
}
function handleOnMouseWheelVertical(event)
{
    vertical.wheel(event);
}

var vertical;

// vertical
function handleOnClickBarVertical2(event) 
{
    vertical2.movescroller(event);
}
function handleOnMouseDownVertical2(event)
{
    vertical2.drag(event);
}
function handleOnClickVertical2(event) 
{
    vertical2.scrollerClickHandler(event);
}
function handleOnMouseWheelVertical2(event)
{
    vertical2.wheel(event);
}

var vertical2;


function init()
{
	if (get("scroller_bar"))
	{
			first = new Scroll('scroller', 'scroller_bar', 'movemenu', 620);
			first.prepare();
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;
			if (get('scroller_next')) get('scroller_next').onclick = handleOnClickBarFirst_next;    
			if (get('scroller_prev')) get('scroller_prev').onclick = handleOnClickBarFirst_prev;   
			 
			get('scroller_bar').onclick = handleOnClickBarFirst;    
			get('scroller').onmousedown = handleOnMouseDownFirst;
			get('scroller').onmouseup = handleOnMouseUp;
			get('scroller').onclick = handleOnClickFirst;    
		
			if (get('withscript').addEventListener)
				get('withscript').addEventListener('DOMMouseScroll', handleOnMouseWheelFirst, false);
			get('withscript').onmousewheel = handleOnMouseWheelFirst;
	}
	
	if (get("scroller_bar2"))
	{
			second = new Scroll('scroller2', 'scroller_bar2', 'movemenu2', 300);
			second.prepare();
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;
			 
			get('scroller_bar2').onclick = handleOnClickBarsecond;    
			get('scroller2').onmousedown = handleOnMouseDownsecond;
			get('scroller2').onmouseup = handleOnMouseUp;
			get('scroller2').onclick = handleOnClicksecond;    
		
			if (get('withscript2').addEventListener)
				get('withscript2').addEventListener('DOMMouseScroll', handleOnMouseWheelsecond, false);
			get('withscript2').onmousewheel = handleOnMouseWheelsecond;
	}
		
	if (get("scroller_bar3"))
	{
			second3 = new Scroll('scroller3', 'scroller_bar3', 'movemenu3', 800);
			second3.prepare();
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;
			if (get('scroller_next3')) get('scroller_next3').onclick = handleOnClickBarsecond3_next;    
			if (get('scroller_prev3')) get('scroller_prev3').onclick = handleOnClickBarsecond3_prev;   
			 
			 
			get('scroller_bar3').onclick = handleOnClickBarsecond3;    
			get('scroller3').onmousedown = handleOnMouseDownsecond3;
			get('scroller3').onmouseup = handleOnMouseUp;
			get('scroller3').onclick = handleOnClicksecond3;    
		
//			if (get('withscript3').addEventListener)
//				get('withscript3').addEventListener('DOMMouseScroll', handleOnMouseWheelsecond3, false);
//			get('withscript3').onmousewheel = handleOnMouseWheelsecond3;
	}
	
	if (get("scroller_bar4"))
	{
			second4 = new Scroll('scroller4', 'scroller_bar4', 'movemenu4', 642);
			second4.prepare();
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;
			if (get('scroller_next4')) get('scroller_next4').onclick = handleOnClickBarsecond4_next;    
			if (get('scroller_prev4')) get('scroller_prev4').onclick = handleOnClickBarsecond4_prev;   
			 
			 
			get('scroller_bar4').onclick = handleOnClickBarsecond4;    
			get('scroller4').onmousedown = handleOnMouseDownsecond4;
			get('scroller4').onmouseup = handleOnMouseUp;
			get('scroller4').onclick = handleOnClicksecond4;    
		
//			if (get('withscript4').addEventListener)
//				get('withscript4').addEventListener('DOMMouseScroll', handleOnMouseWheelsecond4, false);
//			get('withscript4').onmousewheel = handleOnMouseWheelsecond4;
	}
	if (get("scroller_bar5"))
	{
			second5 = new Scroll('scroller5', 'scroller_bar5', 'movemenu5', 620);
			second5.prepare();
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;
			 
			get('scroller_bar5').onclick = handleOnClickBarsecond5;    
			get('scroller5').onmousedown = handleOnMouseDownsecond5;
			get('scroller5').onmouseup = handleOnMouseUp;
			get('scroller5').onclick = handleOnClicksecond5;    
		
			if (get('withscript5').addEventListener)
				get('withscript5').addEventListener('DOMMouseScroll', handleOnMouseWheelsecond5, false);
			get('withscript5').onmousewheel = handleOnMouseWheelsecond5;
	}	
	if (get("scroller_bar_v"))
	{
			vertical = new VerticalScroll('scroller_v', 'scroller_bar_v', 'movemenu_v');			
			vertical.prepare();
			
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;		
			get('scroller_bar_v').onclick = handleOnClickBarVertical;			
			get('scroller_v').onmousedown = handleOnMouseDownVertical;
			get('scroller_v').onmouseup = handleOnMouseUp;
			get('scroller_v').onclick = handleOnClickVertical;   

			if (get('withscript_v').addEventListener)
				get('withscript_v').addEventListener('DOMMouseScroll', handleOnMouseWheelVertical, false);
			get('withscript_v').onmousewheel = handleOnMouseWheelVertical;
	}	
	
	if (get("scroller_bar_v2"))
	{
			vertical2 = new VerticalScroll('scroller_v2', 'scroller_bar_v2', 'movemenu_v2');			
			vertical2.prepare();
			
			document.onmousemove = handleOnMouseMove;
			window.onmouseup = handleOnMouseUp;		
			get('scroller_bar_v2').onclick = handleOnClickBarVertical2;			
			get('scroller_v2').onmousedown = handleOnMouseDownVertical2;
			get('scroller_v2').onmouseup = handleOnMouseUp;
			get('scroller_v2').onclick = handleOnClickVertical2;   

			if (get('withscript_v2').addEventListener)
				get('withscript_v2').addEventListener('DOMMouseScroll', handleOnMouseWheelVertical2, false);
			get('withscript_v2').onmousewheel = handleOnMouseWheelVertical2;
	}	
		
}
window.onload = init;

