// page init
$(function(){
	initScrollBars();
	initTicker();
	initPopups();
	initCufon();
});

// cufon init
function initCufon() {
	Cufon.replace('ul#nav a:not(.active)', { fontFamily: 'AkzidenzGroteskReg', hover: true });
	Cufon.replace('ul#nav a.active', { fontFamily: 'AkzidenzGroteskBold', hover: true });
	Cufon.replace('div.columns  h2 a', { fontFamily: 'AkzidenzGroteskBold', hover: true });
	Cufon.replace('ul.add-nav li a', { fontFamily: 'AkzidenzGroteskReg', hover: true });
	Cufon.replace('div.about-wrapper h2', { fontFamily: 'AkzidenzGroteskBold' });
	Cufon.replace('div.studies-wrapper .section h2 a', { fontFamily: 'AkzidenzGroteskBold', hover: true });
	Cufon.replace('.case-wrapper .block h2', { fontFamily: 'AkzidenzGroteskBold' });
}

// news ticker init
function initTicker() {
	$('div.news').crawlLine({
		speed:2,
		crawElement:'div.news-slider',
		textElement:'ul',
		hoverClass:'viewText'
	});
}

// scrollbars init
function initScrollBars() {
	VSA_initScrollbars();
	
	$('div.hscrollable').corusel({
		slider: 'div.slide-holder',
		sliderEl: 'span',
		holderList: 'div.scrollbox',
		scrollElParent: 'div.holder',
		scrollEl: '> div',
		duration: 1000
	});
}

// popups function
function initPopups() {
	var _zIndex = 1000;
	var _fadeSpeed = 350;
	var _faderOpacity = 0.75;
	var _faderBackground = '#000';
	var _faderId = 'lightbox-overlay';
	var _closeLink = 'a.close, a.cancel';
	var _fader;
	var _lightbox = null;
	var _ajaxClass = 'open-popup';
	var _openers = $('a.open-popup');
	var _page = $('body > div:eq(0)');
	var _minWidth = _page.outerWidth();
	var _scroll = false;

	// init popup fader
	_fader = $('#'+_faderId);
	if(!_fader.length) {
		_fader = $('<div />');
		_fader.attr('id',_faderId);
		$('body').append(_fader);
	}
	_fader.css({
		opacity:_faderOpacity,
		backgroundColor:_faderBackground,
		position:'absolute',
		overflow:'hidden',
		display:'none',
		top:0,
		left:0,
		zIndex:_zIndex
	});

	// IE6 iframe fix
	if(jQuery.browser.msie && jQuery.browser.version < 7) {
		if(!_fader.children().length) {
			var _frame = jQuery('<iframe src="javascript:false" frameborder="0" scrolling="no" />');
			_frame.css({
				opacity:0,
				width:'100%',
				height:'100%'
			})
			_fader.empty().append(_frame);
		}
	}

	// lightbox positioning function
	function positionLightbox() {
		if(_lightbox) {
			var _windowHeight = $(window).height();
			var _windowWidth = $(window).width();
			var _lightboxWidth = _lightbox.outerWidth();
			var _lightboxHeight = _lightbox.outerHeight();
			var _pageHeight = _page.outerHeight(true);

			if (_windowWidth < _minWidth) _fader.css('width',_minWidth);
				else _fader.css('width','100%');
			if (_windowHeight < _pageHeight) _fader.css('height',_pageHeight);
				else _fader.css('height',_windowHeight);

			_lightbox.css({
				position:'absolute',
				zIndex:(_zIndex+1)
			});

			// vertical position
			if (_windowHeight > _lightboxHeight) {
				_lightbox.css({
					top: parseInt($(window).scrollTop()) + (_windowHeight - _lightboxHeight) / 2
				});
			} else {
				var _faderHeight = _fader.height();
				if(_faderHeight < _lightboxHeight) _fader.css('height',_lightboxHeight);
				if (!_scroll) {
					if (_faderHeight - _lightboxHeight > parseInt($(window).scrollTop())) {
						_faderHeight = parseInt($(window).scrollTop())
						_scroll = _faderHeight;
					} else {
						_scroll = _faderHeight - _lightboxHeight;
					}
				}
				_lightbox.css({
					position:'absolute',
					top: _scroll
				});
			}

			// horizontal position
			if (_fader.width() > _lightbox.outerWidth()) _lightbox.css({left:(_fader.width() - _lightbox.outerWidth()) / 2});
			else _lightbox.css({left: 0});
		}
	}

	// show/hide lightbox
	function toggleState(_state) {
		if(!_lightbox) return;
		if(_state) {
			_fader.fadeIn(_fadeSpeed,function(){
				_lightbox.fadeIn(_fadeSpeed);
			});
			_scroll = false;
			positionLightbox();
		} else {
			_lightbox.fadeOut(_fadeSpeed,function(){
				_fader.fadeOut(_fadeSpeed);
				_scroll = false;
			});
		}
	}

	// popup actions
	function initPopupActions(_obj) {
		if(!_obj.get(0).jsInit) {
			_obj.get(0).jsInit = true;

			// close link
			_obj.find(_closeLink).click(function(){
				_lightbox = _obj;
				toggleState(false);
				return false;
			});

			// custom scrolls
			_obj.css({
				position:'absolute',
				top:-9999,
				left:-9999
			}).show();
			var _scrollables = _obj.find('div.hscrollable');
			_scrollables.each(function(){
				var _hold = $(this).find('div.scrollbox');
				var _cont = _hold.find('>div:eq(0)');
				_hold.css({width:_cont.outerWidth()});

				_lightbox.find('div.hscrollable').corusel({
					slider: 'div.slide-holder',
					sliderEl: 'span',
					holderList: 'div.gallery-list',
					scrollElParent: ' > ul',
					scrollEl: '> li',
					duration: 1000
				});
			});
			_obj.hide();

			// cufon init
			Cufon.replace('.case-wrapper .block h2');
		}
	}

	// lightbox openers
	_openers.each(function(){
		var _opener = $(this);
		var _target = _opener.attr('href');

		// popup load type - ajax or static
		if(_opener.hasClass(_ajaxClass)) {
			_opener.click(function(){
				// ajax load
				if($('div[rel*="'+_target+'"]').length == 0) {
					$.ajax({
						url: _target,
						type: "POST",
						dataType: "html",
						success: function(msg){
							// append loaded popup
							_lightbox = $(msg);
							_lightbox.attr('rel',_target).hide().css({
								position:'absolute',
								zIndex:(_zIndex+1),
								top: -9999,
								left: -9999
							});
							$('body').append(_lightbox);

							// init js for lightbox
							initPopupActions(_lightbox);

							// show lightbox
							toggleState(true);
						},
						error: function(msg){
							alert('AJAX error!');
							return false;
						}
					});
				} else {
					_lightbox = jQuery('div[rel*="'+_target+'"]');
					toggleState(true);
				}
				return false;
			});
		} else {
			if($(_target).length) {
				// init actions for popup
				var _popup = $(_target);
				initPopupActions(_popup);
					// open popup
					_opener.click(function(){
					if(_lightbox) {
						_lightbox.fadeOut(_fadeSpeed,function(){
							_lightbox = _popup.hide();
							toggleState(true);
						})
					} else {
						_lightbox = _popup.hide();
						toggleState(true);
					}
					return false;
				});
			}
		}
	});

	// event handlers
	$(window).resize(function(){
		positionLightbox();
	})
	$(window).scroll(function(){
		positionLightbox();
	})
	$(document).keydown(function (e) {
		if (!e) evt = window.event;
		if (e.keyCode == 27) {
			toggleState(false);
		}
	})
	_fader.click(function(){
		if(!_fader.is(':animated')) toggleState(false);
		return false;
	})
}

// corusel width slider ********************************************************
jQuery.fn.corusel = function(_options){
	// defaults options
	var _options = jQuery.extend({
		btPrev: 'a.prev',
		btNext: 'a.next',
		slider: '.slider',
		sliderEl: '.slider',
		holderList: 'div',
		scrollElParent: 'ul',
		scrollEl: 'li',
		duration: 1000
	},_options)

	return this.each(function(){
		var _this = $(this),
			_holderList = $(_options.holderList, _this),
			_mover = $(_options.scrollElParent, _holderList),
			_scrollEl = $(_options.scrollEl, _mover),
			_btNext = $(_options.btNext, _this),
			_btPrev = $(_options.btPrev, _this);

		var _sliderHolder = $(_options.slider, _this),
			_slider = $(_options.sliderEl, _sliderHolder);
		
		var _gWidth = _holderList.innerWidth(),
			_liWidth = _scrollEl.outerWidth(true),
			_sliderHWidth = _sliderHolder.innerWidth(),
			_duration = _options.duration,
			_pos = _sliderHolder.offset(),
			_liSum = 0,
			_left = 0,
			_currentLi,
			_liMargin = [],
			_margin = 0,
			_step = _liWidth;
		
		_liMargin[0] = 0;
		_scrollEl.each(function(i, li){
			_liSum += $(li).outerWidth(true);
			_liMargin[i+1] = _liSum;
		});
		
		var _sliderW = _slider.innerWidth();
		
		var _resizeK = (_sliderHWidth-_sliderW)/100,
			_k = (_sliderHWidth-_sliderW)/(_liSum-_gWidth),
			_stepNav = (_sliderHWidth-_sliderW)/_scrollEl.length;

		if (_liSum <= _gWidth) {
			_btNext.hide();
			_btPrev.hide();
			_slider.hide();
		}
		
		_sliderHolder.click(function(e){
		if (_liSum > _gWidth) {			
			_pos = _sliderHolder.offset();
			_left = e.pageX - _pos.left;
			sliderAnimate();
		}
		});
		
		var _durForAutoSlide = 500 * _scrollEl.length;
		_btNext.mousedown(function(){
			if (_left == _sliderHWidth-_sliderW) return false;
			var _aK = 1 - _left/(_sliderHWidth-_sliderW);
			_slider.stop().animate({left: _sliderHWidth-_sliderW}, {duration:_durForAutoSlide*_aK, easing:'linear', step:function(anmObj){
				_left = anmObj;
				_margin = _left/_k;
			}});
			_margin = (_sliderHWidth-_sliderW)/_k;
			_mover.stop().animate({marginLeft: -_margin}, {duration:_durForAutoSlide*_aK, easing:'linear'});
		}).mouseup(function(){
			_slider.stop();
			_mover.stop();
			autoCentered();
		});
		_btPrev.mousedown(function(){
			if (_left == 0) return false;
			var _aK = _left/(_sliderHWidth-_sliderW);
			_slider.stop().animate({left: 0}, {duration:_durForAutoSlide*_aK, easing:'linear', step:function(anmObj){
				_left = anmObj;
				_margin = _left/_k;
			}});
			_mover.stop().animate({marginLeft:0}, {duration:_durForAutoSlide*_aK, easing:'linear'});
		}).mouseup(function(){
			_slider.stop();
			_mover.stop();
			autoCentered();
		});
				
		$(window).resize(function(){
			_pos = _sliderHolder.offset();
		});
		
		var _timerWheel = false;
		_holderList.bind('wheel',function(event,delta){
			if (_timerWheel) clearTimeout(_timerWheel);
			if (delta > 0) {
				_margin -= 15;
			} else {
				_margin += 15;
			}
			if (_margin < 0) _margin = 0;
			if (_margin > _liSum - _gWidth) _margin = _liSum - _gWidth;
			_mover.css({marginLeft: -_margin});
			_slider.css({left:_margin*_k});
			
			_timerWheel = setTimeout(autoCentered, 800);
		});
				
		function sliderAnimate(){
			_slider.css({left: _left});
			_margin = _left/_k;
			_mover.animate({marginLeft: -_margin}, {duration:300, complete:function(){
				autoCentered();
			}});
		}
		function autoCentered(){
			_margin = Math.round(_margin/_liMargin[1])*_liMargin[1];
			_mover.animate({marginLeft: -_margin}, {duration:300});
			_slider.animate({left:_margin*_k}, {duration:300});
		}
				
		_slider.click(function(){return false});
		var _timerMove = false;
		_slider.mousedown(function(e){
			var _dif = e.pageX - _pos.left;
			var _sl = parseInt(_slider.css('left'));
			$(document).bind('mousemove', function(e){
				_left = e.pageX - _pos.left - _dif + _sl;
				if (_left < 0) {
					_left = 0;
				}
				if (_left > _sliderHWidth-_sliderW) {
					_left = _sliderHWidth-_sliderW;
				}
				_slider.css({left: _left});
				_margin = _left/_k;
				_mover.css({marginLeft: -_margin});
				return false;
			});
			$('body').bind('mouseup', leaveScroll);
			$(document).bind('selectstart', function(){return false;});
			
			function leaveScroll(){
				autoCentered();				
				$(document).unbind('mousemove');
				$('body').unbind('mouseup', leaveScroll);
				$(document).unbind('selectstart', function(){return false;});
				return false;
			}
			return false;
		});
		
	});
}
;(function($){$.fn.wheel=function(a){return this[a?"bind":"trigger"]("wheel",a)};$.event.special.wheel={setup:function(){$.event.add(this,b,wheelHandler,{})},teardown:function(){$.event.remove(this,b,wheelHandler)}};var b=!$.browser.mozilla?"mousewheel":"DOMMouseScroll"+($.browser.version<"1.9"?" mousemove":"");function wheelHandler(a){switch(a.type){case"mousemove":return $.extend(a.data,{clientX:a.clientX,clientY:a.clientY,pageX:a.pageX,pageY:a.pageY});case"DOMMouseScroll":$.extend(a,a.data);a.delta=-a.detail/3;break;case"mousewheel":a.delta=a.wheelDelta/120;if($.browser.opera)a.delta*=-1;break}a.type="wheel";return $.event.handle.call(this,a,a.delta)}})(jQuery);

var VSA_scrollAreas = new Array();
var currentLocation = window.location.href;
var VSA_default_imagesPath = "/images";
var VSA_default_btnUpImage = "button-up.gif";
var VSA_default_btnDownImage = "button-down.gif";
if (currentLocation.indexOf("architecture") != -1) {
	var VSA_default_btnUpImage = "button-upGreen.gif";
	var VSA_default_btnDownImage = "button-downGreen.gif";
}
if (currentLocation.indexOf("digital") != -1) {
	var VSA_default_btnUpImage = "button-upOrange.gif";
	var VSA_default_btnDownImage = "button-downOrange.gif";
}
if (currentLocation.indexOf("event") != -1) {
	var VSA_default_btnUpImage = "button-upBlue.gif";
	var VSA_default_btnDownImage = "button-downBlue.gif";
}
if (currentLocation.indexOf("telephony") != -1) {
	var VSA_default_btnUpImage = "button-upPink.gif";
	var VSA_default_btnDownImage = "button-downPink.gif";
}
var VSA_default_scrollStep = 5;
var VSA_default_wheelSensitivity = 10;
var VSA_default_scrollbarPosition = 'right';//'left','right','inline';
var VSA_default_scrollButtonHeight = 9;
var VSA_default_scrollbarWidth = 14;
var VSA_resizeTimer = 2000;

function VSA_initScrollbars() {
	var scrollElements = VSA_getElements("vscrollable", "DIV", document, "class");
	for (var i=0; i<scrollElements.length; i++)
	{
		VSA_scrollAreas[i] = new VScrollArea(i, scrollElements[i]);
	}
}

function VScrollArea(index, elem) //constructor
{
	this.index = index;
	this.element = elem;

	var attr = this.element.getAttribute("imagesPath");
	this.imagesPath = attr ? attr : VSA_default_imagesPath;

	attr = this.element.getAttribute("btnUpImage");
	this.btnUpImage = attr ? attr : VSA_default_btnUpImage;

	attr = this.element.getAttribute("btnDownImage");
	this.btnDownImage = attr ? attr : VSA_default_btnDownImage;

	attr = Number(this.element.getAttribute("scrollStep"));
	this.scrollStep = attr ? attr : VSA_default_scrollStep;

	attr = Number(this.element.getAttribute("wheelSensitivity"));
	this.wheelSensitivity = attr ? attr : VSA_default_wheelSensitivity;

	attr = this.element.getAttribute("scrollbarPosition");
	this.scrollbarPosition = attr ? attr : VSA_default_scrollbarPosition;

	attr = this.element.getAttribute("scrollButtonHeight");
	this.scrollButtonHeight = attr ? attr : VSA_default_scrollButtonHeight;

	attr = this.element.getAttribute("scrollbarWidth");
	this.scrollbarWidth = attr ? attr : VSA_default_scrollbarWidth;

	this.scrolling = false;

	this.iOffsetY = 0;
	this.scrollHeight = 0;
	this.scrollContent = null;
	this.scrollbar = null;
	this.scrollup = null;
	this.scrolldown = null;
	this.scrollslider = null;
	this.scroll = null;
	this.enableScrollbar = false;
	this.scrollFactor = 1;
	this.scrollingLimit = 0;
	this.topPosition = 0;

	//functions declaration
	this.init = VSA_init;
	this.scrollUp = VSA_scrollUp;
	this.scrollDown = VSA_scrollDown;
	this.createScrollBar = VSA_createScrollBar;
	this.scrollIt = VSA_scrollIt;
	this.init();
}


function VSA_init()
{
	this.scrollContent = document.createElement("DIV");
	this.scrollContent.style.position = "absolute";
	this.scrollContent.innerHTML = this.element.innerHTML;
	this.scrollContent.style.overflow = "hidden";

	this.scrollContent.style.width = this.element.offsetWidth + "px";
	this.scrollContent.style.height = this.element.offsetHeight + "px";

	this.element.innerHTML = "";
	this.element.style.overflow = "hidden";
	this.element.style.display = "block";
	this.element.style.visibility = "visible";
	this.element.style.position = "relative";
	this.element.appendChild(this.scrollContent);

	this.scrollContent.className = 'scroll-content';
	this.element.index = this.index;
	this.element.over = false;

	var _this = this;
	this.element.onmouseover = function(){
        _this.element.over = true;
    };
    this.element.onmouseout = function(){
        _this.element.over = false;
    }

	if (document.all)
	{
		this.element.onscroll = VSA_handleOnScroll;
		this.element.onresize = VSA_handleResize;
	}
	else
	{
		window.onresize = VSA_handleResize;
	}

	this.createScrollBar();

	if (window.addEventListener)
        /** DOMMouseScroll is for mozilla. */
        this.element.addEventListener('DOMMouseScroll', VSA_handleMouseWheel, false);
	/** IE/Opera. */
	this.element.onmousewheel = document.onmousewheel = VSA_handleMouseWheel;

}

function VSA_createScrollBar()
{

	if (this.scrollbar != null)
	{
		this.element.removeChild(this.scrollbar);
		this.scrollbar = null;
	}

	if (this.scrollContent.scrollHeight <= this.scrollContent.offsetHeight)
		this.enableScrollbar = false;
	else if (this.element.offsetHeight > 2*this.scrollButtonHeight)
		this.enableScrollbar = true;
	else
		this.enableScrollbar = false;

	if (this.scrollContent.scrollHeight - Math.abs(this.scrollContent.scrollTop) < this.element.offsetHeight)
		this.scrollContent.style.top = 0;

	if (this.enableScrollbar)
	{

		this.scrollbar = document.createElement("DIV");
		this.element.appendChild(this.scrollbar);
		this.scrollbar.style.position = "absolute";
		this.scrollbar.style.top = "0px";
		this.scrollbar.style.height = this.element.offsetHeight+"px";
		this.scrollbar.style.width = this.scrollbarWidth + "px";

		this.scrollbar.className = 'vscroll-bar';

		if(this.scrollbarWidth != this.scrollbar.offsetWidth)
		{
			this.scrollbarWidth = this.scrollbar.offsetHeight;
		}

		this.scrollbarWidth = this.scrollbar.offsetWidth;

		if(this.scrollbarPosition == 'left')
		{
			this.scrollContent.style.left = this.scrollbarWidth + 5 + "px";
			this.scrollContent.style.width = this.element.offsetWidth - this.scrollbarWidth - 5 + "px";
		}
		else if(this.scrollbarPosition == 'right')
		{
			this.scrollbar.style.left = this.element.offsetWidth - this.scrollbarWidth  + "px";
			this.scrollContent.style.width = this.element.offsetWidth - this.scrollbarWidth - 5 + "px";
		}

		//create scroll up button
		this.scrollup = document.createElement("DIV");
		this.scrollup.index = this.index;
		this.scrollup.onmousedown = VSA_handleBtnUpMouseDown;
		this.scrollup.onmouseup = VSA_handleBtnUpMouseUp;
		this.scrollup.onmouseout = VSA_handleBtnUpMouseOut;
		this.scrollup.style.position = "absolute";
		this.scrollup.style.top = "0px";
		this.scrollup.style.left = "0px";
		this.scrollup.style.height = this.scrollButtonHeight + "px";
		this.scrollup.style.width = this.scrollbarWidth + "px";

		this.scrollup.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnUpImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrollup);

		this.scrollup.className = 'vscroll-up';

		if(this.scrollButtonHeight != this.scrollup.offsetHeight)
		{
			this.scrollButtonHeight = this.scrollup.offsetHeight;
		}

		//create scroll down button
		this.scrolldown = document.createElement("DIV");
		this.scrolldown.index = this.index;
		this.scrolldown.onmousedown = VSA_handleBtnDownMouseDown;
		this.scrolldown.onmouseup = VSA_handleBtnDownMouseUp;
		this.scrolldown.onmouseout = VSA_handleBtnDownMouseOut;
		this.scrolldown.style.position = "absolute";
		this.scrolldown.style.left = "0px";
		this.scrolldown.style.top =  this.scrollbar.offsetHeight - this.scrollButtonHeight + "px";
		this.scrolldown.style.width = this.scrollbarWidth + "px";
		this.scrolldown.innerHTML = '<img src="' + this.imagesPath + '/' + this.btnDownImage + '" border="0"/>';
		this.scrollbar.appendChild(this.scrolldown);

		this.scrolldown.className = 'vscroll-down';

		//create scroll
		this.scroll = document.createElement("DIV");
		this.scroll.index = this.index;
		this.scroll.style.position = "absolute";
		this.scroll.style.zIndex = 0;
		this.scroll.style.textAlign = "center";
		this.scroll.style.top = this.scrollButtonHeight + "px";
		this.scroll.style.left = "0px";
		this.scroll.style.width = this.scrollbarWidth + "px";

		var h = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight;
		this.scroll.style.height = ((h > 0) ? h : 0) + "px";

		this.scroll.innerHTML = '';
		this.scroll.onclick = VSA_handleScrollbarClick;
		this.scrollbar.appendChild(this.scroll);
		this.scroll.style.overflow = "hidden";

		this.scroll.className = "vscroll-line";

		//create slider
		this.scrollslider = document.createElement("DIV");
		this.scrollslider.index = this.index;
		this.scrollslider.style.position = "absolute";
		this.scrollslider.style.zIndex = 1000;
		this.scrollslider.style.textAlign = "center";
		this.scrollslider.innerHTML = '<div id="scrollslider' + this.index + '" style="padding:0;margin:0;"><div class="scroll-bar-top"></div><div class="scroll-bar-bottom"></div></div>';
		this.scrollbar.appendChild(this.scrollslider);

		this.subscrollslider = document.getElementById("scrollslider"+this.index);
		this.subscrollslider.style.height = Math.round((this.scrollContent.offsetHeight/this.scrollContent.scrollHeight)*(this.scrollbar.offsetHeight - 2*this.scrollButtonHeight)) + "px";

		this.scrollslider.className = "vscroll-slider";

		this.scrollHeight = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight - this.scrollslider.offsetHeight;
		this.scrollFactor = (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight)/this.scrollHeight;
		this.topPosition = getRealTop(this.scrollbar) + this.scrollButtonHeight;
		/* this.scrollbarHeight = this.scrollbar.offsetHeight - 2*this.scrollButtonHeight - this.scrollslider.offsetHeight; */

		this.scrollslider.style.top = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollTop) + this.scrollButtonHeight + "px";
		this.scrollslider.style.left = "0px";
		this.scrollslider.style.width = "100%";
		this.scrollslider.onmousedown = VSA_handleSliderMouseDown;
		if (document.all)
			this.scrollslider.onmouseup = VSA_handleSliderMouseUp;
	}
	else
		this.scrollContent.style.width = this.element.offsetWidth + "px";
}

function VSA_handleBtnUpMouseDown()
{
	var sa = VSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollUp();
}

function VSA_handleBtnUpMouseUp()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnUpMouseOut()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnDownMouseDown()
{
	var sa = VSA_scrollAreas[this.index];
	sa.scrolling = true;
	sa.scrollDown();
}

function VSA_handleBtnDownMouseUp()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_handleBtnDownMouseOut()
{
	VSA_scrollAreas[this.index].scrolling = false;
}

function VSA_scrollIt()
{
	this.scrollContent.scrollTop = this.scrollFactor * ((this.scrollslider.offsetTop + this.scrollslider.offsetHeight/2) - this.scrollButtonHeight - this.scrollslider.offsetHeight/2);
}

function VSA_scrollUp()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;
	if ( this.scrollContent.scrollTop - this.scrollStep > 0)
	{
		this.scrollContent.scrollTop -= this.scrollStep;
		this.scrollslider.style.top = 1 / this.scrollFactor * Math.abs(this.scrollContent.scrollTop) + this.scrollButtonHeight + "px";
	}
	else
	{
		this.scrollContent.scrollTop = "0";
		this.scrollslider.style.top = this.scrollButtonHeight + "px";
		return;
	}
	setTimeout("VSA_Ext_scrollUp(" + this.index + ")", 30);
}

function VSA_Ext_scrollUp(index)
{
	VSA_scrollAreas[index].scrollUp();
}

function VSA_scrollDown()
{
	if (this.scrollingLimit > 0)
	{
		this.scrollingLimit--;
		if (this.scrollingLimit == 0) this.scrolling = false;
	}
	if (!this.scrolling) return;


	this.scrollContent.scrollTop += this.scrollStep;
	this.scrollslider.style.top =  1 / this.scrollFactor * Math.abs(this.scrollContent.scrollTop) + this.scrollButtonHeight + "px";

	if (this.scrollContent.scrollTop >= (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight))
	{
		this.scrollContent.scrollTop = (this.scrollContent.scrollHeight - this.scrollContent.offsetHeight);
		this.scrollslider.style.top = this.scrollbar.offsetHeight - this.scrollButtonHeight - this.scrollslider.offsetHeight + "px";
		return;
	}

	setTimeout("VSA_Ext_scrollDown(" + this.index + ")", 30);
}

function VSA_Ext_scrollDown(index)
{
	VSA_scrollAreas[index].scrollDown();
}

function VSA_handleMouseMove(evt)
{
	var sa = VSA_scrollAreas[((document.all && !window.opera) ? this.index : document.documentElement.scrollAreaIndex)];
	var posy = 0;
	if (!evt) var evt = window.event;

	if (evt.pageY)
		posy = evt.pageY;
	else if (evt.clientY)
		posy = evt.clientY;

		if (document.all && !window.opera)
		{
			posy += document.documentElement.scrollTop;
		}

	var iNewY = posy - sa.iOffsetY - sa.topPosition;
		iNewY += sa.scrollButtonHeight;

	if (iNewY < sa.scrollButtonHeight)
		iNewY = sa.scrollButtonHeight;
	if (iNewY > (sa.scrollbar.offsetHeight - sa.scrollButtonHeight) - sa.scrollslider.offsetHeight)
		iNewY = (sa.scrollbar.offsetHeight - sa.scrollButtonHeight) - sa.scrollslider.offsetHeight;

	sa.scrollslider.style.top = iNewY + "px";

	sa.scrollIt();
}

function VSA_handleSliderMouseDown(evt)
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onselectstart = function() { return false; }
		document.onmousedown = function() { return false; }
	}

	var sa = VSA_scrollAreas[this.index];
	if (document.all && !window.opera)
	{
		sa.scrollslider.setCapture()
		sa.iOffsetY = event.offsetY;
		sa.scrollslider.onmousemove = VSA_handleMouseMove;
	}
	else
	{
		if(window.opera)
		{
			sa.iOffsetY = event.offsetY;
		}
		else
		{
			sa.iOffsetY = evt.layerY;
		}
		document.documentElement.scrollAreaIndex = sa.index;
		document.documentElement.addEventListener("mousemove", VSA_handleMouseMove, true);
		document.documentElement.addEventListener("mouseup", VSA_handleSliderMouseUp, true);
	}
	return false;
}

function VSA_handleSliderMouseUp()
{
	if (!(document.uniqueID && document.compatMode && !window.XMLHttpRequest))
	{
		document.onmousedown = null;
		document.onselectstart = null;
	}

	if (document.all && !window.opera)
	{
		var sa = VSA_scrollAreas[this.index];
		sa.scrollslider.onmousemove = null;
		sa.scrollslider.releaseCapture();
		sa.scrollIt();
	}
	else
	{
		var sa = VSA_scrollAreas[document.documentElement.scrollAreaIndex];
		document.documentElement.removeEventListener("mousemove", VSA_handleMouseMove, true);
		document.documentElement.removeEventListener("mouseup", VSA_handleSliderMouseUp, true);
		sa.scrollIt();
	}
	return false;
}

function VSA_handleResize()
{
	if (VSA_resizeTimer)
	{
		clearTimeout(VSA_resizeTimer);
		VSA_resizeTimer = 0;
	}
	VSA_resizeTimer = setTimeout("VSA_performResizeEvent()", 100);
}

function VSA_performResizeEvent()
{
	for (var i=0; i<VSA_scrollAreas.length; i++)
		VSA_scrollAreas[i].createScrollBar();
}
function VSA_handleMouseWheel(event){
	if (this.index != null) {
		var sa = VSA_scrollAreas[this.index];

		if (sa.scrollbar == null) return;
		sa.scrolling = true;
		sa.scrollingLimit = sa.wheelSensitivity;

        var delta = 0;
        if (!event) /* For IE. */
                event = window.event;
        if (event.wheelDelta) { /* IE/Opera. */
                delta = event.wheelDelta/120;

                /*if (window.opera)
                        delta = -delta;*/
        } else if (event.detail) { /** Mozilla case. */
                delta = -event.detail/3;
        }
        if (delta && sa.element.over) {
                if (delta > 0)
			        sa.scrollUp();
				else
			        sa.scrollDown();

                if (event.preventDefault)
                        event.preventDefault();
                event.returnValue = false;
        }
	}
}

function VSA_handleSelectStart()
{
	event.returnValue = false;
}

function VSA_handleScrollbarClick(evt)
{
	var sa = VSA_scrollAreas[this.index];
	var offsetY = (document.all ? event.offsetY : evt.layerY);

	if (offsetY < (sa.scrollButtonHeight + sa.scrollslider.offsetHeight/2))
		sa.scrollslider.style.top = sa.scrollButtonHeight + "px";
	else if (offsetY > (sa.scrollbar.offsetHeight - sa.scrollButtonHeight - sa.scrollslider.offsetHeight))
		sa.scrollslider.style.top = sa.scrollbar.offsetHeight - sa.scrollButtonHeight - sa.scrollslider.offsetHeight + "px";
	else
	{
		sa.scrollslider.style.top = offsetY + sa.scrollButtonHeight - sa.scrollslider.offsetHeight/2 + "px";
	}
	sa.scrollIt();
}

function VSA_handleOnScroll()
{
	//event.srcElement.doScroll("pageUp");
}

//--- common functions ----

function VSA_getElements(attrValue, tagName, ownerNode, attrName) //get Elements By Attribute Name
{
	if (!tagName) tagName = "*";
	if (!ownerNode) ownerNode = document;
	if (!attrName) attrName = "name";
	var result = [];
	var nl = ownerNode.getElementsByTagName(tagName);
	for (var i=0; i<nl.length; i++)
	{
	//	if (nl.item(i).getAttribute(attrName) == attrValue)
//		result.push(nl.item(i));
		if (nl.item(i).className.indexOf(attrValue) != -1)
		result.push(nl.item(i));
	}
	return result;
}

var _ie = (navigator.userAgent.toLowerCase().indexOf("msie") != -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1);

function getRealTop(elem)
{
	if(_ie) {
		var nTop = 0;
		if(elem)
		{
			do
			{
				nTop += elem.offsetTop - elem.scrollTop;
				elem = elem.offsetParent;
			}
			while(elem)
		}
		return nTop;
	}
	else {
		var posTop = 0;
		while (elem.offsetParent) {
			posTop += elem.offsetTop;
			elem = elem.offsetParent;
		}
		var _res = new Object();
		return posTop;
	}
}

/*******************************************************************************************/
// jquery.event.wheel.js - rev 1
// Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
// Liscensed under the MIT License (MIT-LICENSE.txt)
// http://www.opensource.org/licenses/mit-license.php
// Created: 2008-07-01 | Updated: 2008-07-14
// $(body).bind('wheel',function(event,delta){	alert( delta>0 ? "up" : "down" );	});
/*******************************************************************************************/
;(function($){$.fn.wheel=function(a){return this[a?"bind":"trigger"]("wheel",a)};$.event.special.wheel={setup:function(){$.event.add(this,b,wheelHandler,{})},teardown:function(){$.event.remove(this,b,wheelHandler)}};var b=!$.browser.mozilla?"mousewheel":"DOMMouseScroll"+($.browser.version<"1.9"?" mousemove":"");function wheelHandler(a){switch(a.type){case"mousemove":return $.extend(a.data,{clientX:a.clientX,clientY:a.clientY,pageX:a.pageX,pageY:a.pageY});case"DOMMouseScroll":$.extend(a,a.data);a.delta=-a.detail/3;break;case"mousewheel":a.delta=a.wheelDelta/120;if($.browser.opera)a.delta*=-1;break}a.type="wheel";return $.event.handle.call(this,a,a.delta)}})(jQuery);
jQuery.fn.crawlLine = function(_options){
	// defaults options
	var _options = jQuery.extend({
		speed:2,
		crawElement:'div',
		textElement:'p',
		hoverClass:'viewText'
	},_options);

	return this.each(function(){
		var _THIS = jQuery(this);
		var _el = $(_options.crawElement, _THIS);
		var _text = $(_options.textElement, _THIS);
		var _clone = _text.css('whiteSpace','nowrap').clone();
		var _elWidth = 0;
		var _k = 1;

		// set parametrs *******************************************************
		var _textWidth = _text.outerWidth(true);
		if(_textWidth < _THIS.width()) return;

		var _duration = _textWidth*50 / _options.speed;
		_text.after(_clone);
		_el.css('width',_textWidth*2);

		var animate = function() {
			_el.animate({marginLeft:-_textWidth}, {queue:false, duration:_duration*_k, easing:'linear', complete:function(){
				_el.css('marginLeft','0');
				_k=1;
				animate();
			}})
		}
		animate();

		_THIS.hover(function() {
			_el.stop();
			_THIS.addClass(_options.hoverClass);
		}, function(){
			_THIS.removeClass(_options.hoverClass);
			_k = (_textWidth + parseInt(_el.css('marginLeft')))/_textWidth;
			animate();
		})

		_THIS.bind('wheel',function(event,delta){
			var _marginScroll;
			if (delta>0) {
				_marginScroll = parseInt(_el.css('marginLeft')) - 20;
				_el.animate({marginLeft:_marginScroll}, {queue:false, duration:100, easing:'linear', complete:function(){
					_k = (_textWidth + parseInt(_el.css('marginLeft')))/_textWidth;
				}})
			} else {
				_marginScroll = parseInt(_el.css('marginLeft')) + 20;
				if (_marginScroll > 0) _marginScroll = 0;
				_el.animate({marginLeft:_marginScroll}, {queue:false, duration:100, easing:'linear', complete:function(){
					_k = (_textWidth + parseInt(_el.css('marginLeft')))/_textWidth;
				}})
			}
		});
	});
}
