function handle(delta)
{
	if (delta < 0) coord=coord-18;
	else coord=coord+18;
	if (-coord > mess.offsetHeight) coord = sms.offsetHeight - 2;
	if ( coord > sms.offsetHeight) coord = -mess.offsetHeight;
	mess.style.marginTop = coord +'px';
}
function cancelEvent(e)
{
	e = e ? e : window.event;
	if (e.stopPropagation) e.stopPropagation();
	if (e.preventDefault) e.preventDefault();
	e.cancelBubble = true;
	e.cancel = true;
	e.returnValue = false;
	return false;
}
function defPosition(event) 
{
	var x = 0;
	if (document.attachEvent != null) {
		x = window.event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
	} else if (!document.attachEvent && document.addEventListener) {
		x = event.clientX + window.scrollX;
	}
	return {x:x};
}


/**
 * Класс SibSlider
 * 
 * @copyright Siberian
 * @author Kevin <grieve@ya.ru> & Paskam <paskam@r41.ru>
 */

 /**
 * Конструктор
 * @param object init набор параметров
 */
function SibSlider(init, arr) 
{
    this.v.idSlider   = init.idSlider;
    this.v.idList     = init.idList;
    this.v.blockWidth = init.blockWidth;
    // DOM-объекты
    this.dom.cont   = document.getElementById(this.v.idConteiner);
    this.dom.slider = document.getElementById(this.v.idSlider);
    this.dom.list   = document.getElementById(this.v.idList);
    this.dom.scroll = document.getElementById('scroll-bar');
    
    // Кол-во блоков
    this.v.blocksCount = arr.length;

    // Считываем ширину скролл-контейнера
    this.calcSliderWidth();
    window.onresize = function() {
    	SibSlider.prototype.calcSliderWidth();
    	SibSlider.prototype.v.blocksOnScreen = Math.ceil(SibSlider.prototype.v.sliderWidth / SibSlider.prototype.v.blockWidth);
    	SibSlider.prototype.v.center = Math.round(SibSlider.prototype.v.sliderWidth/2 - SibSlider.prototype.v.blockWidth/2);
    };
    // Устанавливаем ширину для списка блоков
    this.dom.list.style.width = ((arr.length+1) * this.v.blockWidth) + 'px';   
    // Строим список блоков
    this.v.arr = arr;
    this.buildBlocks(arr);
    // Вычисляем количеество блоков, которое помещается на страницу
    this.v.blocksOnScreen = Math.ceil(this.v.sliderWidth / this.v.blockWidth);
    // TODO: центр
    this.v.center = Math.round(this.v.sliderWidth/2 - this.v.blockWidth/2);
    // TODO: придумать комментарий. Последний сдвиг
    this.v.last = this.v.center + this.v.blockWidth;
    // Показать блоки
    for (var i=0; i<this.v.blocksOnScreen * 2; i++) {
		
    	this.v.visibleLast = this.show(i, 'right');
    }
	this.v.curent = this.searchUrl();
    this.setImg(this.searchUrl());
    // Ширина всех блоков
    this.v.iWidth = this.v.blocksCount * this.v.blockWidth;
    // Ширина скролл-бара
    var scrollWidth = Math.round( Math.pow(this.v.sliderWidth, 2) / (arr.length * this.v.blockWidth) );
    this.dom.scroll.style.width = scrollWidth + 'px';
	// Назначем событие передвижение ползунка
	this.dom.scroll.onmouseup = document.onmouseup = function(event) {
		SibSlider.prototype.v.move = false;
		SibSlider.prototype.v.prevCoord = defPosition(event).x;
	}
	this.dom.scroll.onmousedown	= function(event) {
		SibSlider.prototype.v.move = true;
		SibSlider.prototype.dom.scroll.focus();
		SibSlider.prototype.v.prevCoord = defPosition(event).x;
	}
	//alert(arr.length + ' < '+ this.v.blocksOnScreen);
	if (arr.length < this.v.blocksOnScreen)
	{
		document.getElementById('scroll-bar').style.display="none";
	}
	document.onkeydown = function(e) {
		e = (window.event) ? window.event : e;
		if (e.ctrlKey) {
			if (e.keyCode == 37) SibSlider.prototype.prev();
			if (e.keyCode == 39) SibSlider.prototype.next();
		}
	}
	document.onmousemove = function(event) 
	{
		var sib = SibSlider.prototype;
		var event = event || window.event;
		if (sib.v.move == true) {
			var curCoord = defPosition(event).x; // Получаем текущую координату
			var margin = Number( sib.dom.scroll.style.marginLeft.replace(/px/i, '') ); // получаем отступ у скролл-бара

			var mv =  margin + (curCoord - sib.v.prevCoord); // Место назначения для скролл-бара
			var side = (curCoord - sib.v.prevCoord); // Сторона движения (влево: отрицательно; вправо: положительное)

			var max = sib.v.sliderWidth - scrollWidth; // Максимальный маргин
			mv = (mv < 0) ? 0 : (mv > max) ? max : mv; //  Место назначения для скролл-бара (с учетом начала и конца)
			sib.dom.scroll.style.marginLeft = mv +'px'; // установить марнин
			
			sib.v.prevCoord = curCoord; // записываем последнюю координату
			
			// показываем нужные блоки
			var target = mv * Math.ceil(sib.v.iWidth / sib.v.sliderWidth);// - sib.v.center;
			
			var maxTarget = sib.v.iWidth - sib.v.sliderWidth;
			target = (target>maxTarget) ? maxTarget : target;
			sib.showFast(target);
		}
		
	}
	
	// Назначем событие прокрутики колесиком мышки    
    if (this.dom.cont.addEventListener) this.dom.cont.addEventListener('DOMMouseScroll', this.wheelImg, false);
	this.dom.cont.onmousewheel = this.dom.cont.onmousewheel = this.wheelImg;
}
SibSlider.prototype =
{
	// Глобальные переменные
	v: {
		arr:0,
		// Текущая фотография
		curent: 0,
		// Флаг движения ползунка
		move: false,
		prevCoord: 0,
		// массив показанных элементов
		arrShownBlocks: new Array(),// new Array,
		// StyleID для скролирующего блока
		idConteiner: 'sib-slider',
		idSlider: 'sib-slider-scroll',
		idList:   'sib-slider-list',
		// кол-во блоков
		blocksCount: 0,		// Количество всех блоков
		// Размеры блоков
		iWidth:		 0,		// Ширина всех блоков
		blockWidth:  0,     // Ширина одного блока
		sliderWidth: 0,     // Ширина скроллирующего-контейнера
		// Отступы
		aMargin: 0, // Отступ у блока
		iMargin: 0, // Идеальный отступ у блока без учета убранных блоков
		//
		blocking:       '', // блокиратор
		center:			0,
		visibleFirst:   0,
		visibleLast:    0,
		last:           0, // TODO: надо обозвать
		blocksOnScreen: 0  // Блоков на страницу (видимую часть)
	},
	dom: {
		cont:   null,
		slider: null,
		scroll: null,
		list:   null
	},
	
	// Поиск якоря
	searchUrl: function()
	{
		urlArr = document.location.toString().split("#");
		if (urlArr[1] != undefined && urlArr[1] > 0 && urlArr[1] < this.v.blocksCount)
		{
			return urlArr[1];
		}
		return 0;
	}, 
	// Прокрутка мышкой
	wheelImg: function(event)
	{
		var delta = 0;
		var im = slider.v.iMargin < slider.v.center ? slider.v.center : slider.v.iMargin;
		if (!event) event = window.event;
		if (event.wheelDelta) delta = event.wheelDelta/120;
		else if (event.detail) delta = -event.detail/3;
		if (delta > 0) slider.scrollImgLeft(im-slider.v.blockWidth, 20); else  slider.scrollImg(im+slider.v.blockWidth, 20);
		return cancelEvent(event);
	},
	

	oneLeft: function()
	{
		var im = this.v.iMargin < this.v.center ? this.v.center : this.v.iMargin;
		this.scrollImgLeft(im - this.v.blockWidth, 20);
	},

	oneRight: function()
	{
		var im = this.v.iMargin < this.v.center ? this.v.center : this.v.iMargin;
		this.scrollImg(im + this.v.blockWidth, 20);
	},
	
	
	/**
	 * Построить список блоков
	 */
	buildBlocks: function(arr)
	{
		var count = arr.length;
		// alert(count);
		var blocks = '';
		for(var i=0; i<count; i++)
		{
			blocks += '<div id="b'+ i +'" style="width:'+ this.v.blockWidth 
					+ 'px"><a href="" onclick="slider.setImg('+ i +'); return false"><img style="width:' + this.v.blockWidth + 'px" src="" id="img-' + i + '" alt="..."/><br/>' + arr[i][1] + '</a></div>';
		}
		this.dom.list.innerHTML = blocks;
	},
	
    /**
     * Перейти к нужной картинке
     */
	setImg: function(ind)
	{
		// Убираем с предыдущей фотографии класс-метку, что это текущий блок
		document.getElementById('b'+this.v.curent).className = '';
		// Устанавливаем класс на текущий блок
		document.getElementById('b'+ind).className = 'cur';
		// Записываем в глобаьную переменную индекс текущего блока
		this.v.curent = Number(ind);
		var target = ind * this.v.blockWidth;
		var dist = Math.abs(this.v.iMargin - target);
		var speed = (dist < this.v.sliderWidth/2) ? 20 : Math.ceil(dist * 0.021);
		speed = speed > this.v.blockWidth ? this.v.blockWidth : speed;
		if (0 < this.v.iMargin-target) this.scrollImgLeft(target, speed);
		else this.scrollImg(target, speed);
		
		document.location.href = '#'+ind;
		document.getElementById('picbig').src = this.v.arr[ind][2] + '/used/' + this.v.arr[ind][0];
	},
	
	// переход на следующий блок
	next: function()
	{
		var next = this.v.curent+1;
		next = next < this.v.blocksCount ? next : 0;
		this.setImg(next);
	},
	// переход на следующий блок
	prev: function()
	{
		var prev = this.v.curent-1;
		prev = prev > 0 ? prev : 0;
		this.setImg(prev);
	},
	slideshowStart: function(t)
	{
		if (typeof t == "undefined") t = 1000;
		this.next();
		setTimeout('SibSlider.prototype.slideshowStart('+t+')', t);
	},
	/**
	 * плавная прокрутка LEFT
	 */
	scrollImgLeft: function(target, speed)
	{
		if (this.v.blocking == 'right') return;
		this.v.blocking = 'left';
		// рассчет цели для ограничения последнего блока
		var maxTarget = (this.v.blocksCount-1) * this.v.blockWidth - this.v.center;
		target = (this.v.iMargin > maxTarget) ? maxTarget : target;

		// скролл бар
		this.dom.scroll.style.marginLeft = Math.round( (this.v.sliderWidth / (this.v.arr.length * this.v.blockWidth)) * (this.v.iMargin - this.v.center) ) + 'px';
		
		
		if (this.v.iMargin > target) {
			// Добавляем и убираем блоки
			if (this.v.iMargin - this.v.last <= this.v.blockWidth && this.v.visibleFirst > 0)
			{
				this.v.last -= this.v.blockWidth;
				this.v.visibleFirst = this.show(this.v.visibleFirst - 1, 'left');
				this.hide(this.v.visibleLast, 'left');
				this.v.visibleLast--;
			}
			
			// Расчитываем отступ для блоков
			this.v.aMargin = (this.v.iMargin - (this.v.visibleFirst * this.v.blockWidth)) - this.v.center;
			
			// Расчет цели для корректного перехода в начале движения
			if (this.v.aMargin < 0) {
				this.v.aMargin = 0;
				this.v.iMargin -= speed;
				this.scrollImgLeft(target, speed);
				return;
			}
			
			this.dom.list.style.marginLeft = -this.v.aMargin + 'px';
			// на второй круг
			this.v.iMargin -= speed;
			setTimeout('SibSlider.prototype.scrollImgLeft('+ target +', '+ speed +')', 20);
		}
		else // выравнивание
		{
			this.v.blocking = '';
			if (this.v.iMargin - this.v.center > 0) 	{
				this.v.iMargin = target;
				this.v.aMargin = this.v.iMargin - (this.v.visibleFirst * this.v.blockWidth) - this.v.center;
				this.dom.list.style.marginLeft = -this.v.aMargin + 'px';
			} else {
				this.v.iMargin = this.v.center;
				this.v.aMargin = 0;
				this.dom.list.style.marginLeft = -this.v.aMargin + 'px';
			}
		}
		
		// скролл бар
		this.dom.scroll.style.marginLeft = Math.round( (this.v.sliderWidth / (this.v.arr.length * this.v.blockWidth)) * (this.v.iMargin - this.v.center) ) + 'px';
	},
	
	/**
	 * плавная прокрутка RIGHT
	 */
	scrollImg: function(target, speed)
	{
		// Проверка на блокировку движения
		if (this.v.blocking == 'left') return;
		// Устанавливаем блокировку на движение вправо
		this.v.blocking = 'right';
		
		// рассчет цели для ограничения последнего блока
		var maxTarget = (this.v.blocksCount-1) * this.v.blockWidth - this.v.center;
		target = (this.v.iMargin > maxTarget) ? maxTarget : target;

		
		if (this.v.iMargin < target) {
			// Добавляем и убираем блоки
			if (this.v.iMargin - this.v.last >= this.v.blockWidth) {
				this.v.last += this.v.blockWidth;
				this.v.visibleFirst = this.hide(this.v.visibleFirst, 'right');
				this.v.visibleLast  = this.show(this.v.visibleLast+1, 'right');
			}
			
			// Расчитываем отступ для блоков
			this.v.aMargin = (this.v.iMargin - (this.v.visibleFirst * this.v.blockWidth)) - this.v.center;
			
			// Расчет цели для корректного перехода в начале движения
			if (this.v.aMargin < 0) {
				this.v.aMargin = 0;
				this.v.iMargin += speed;
				this.scrollImg(target, speed);
				return;
			}
			
			this.dom.list.style.marginLeft = -this.v.aMargin + 'px';
			// на второй круг
			this.v.iMargin += speed;
			setTimeout('SibSlider.prototype.scrollImg('+ target +', '+ speed +')', 20);
		}
		else // выравнивание
		{	
			this.v.blocking = ''; // Отменяем блокировку
			if (this.v.iMargin - this.v.center > 0) {
				this.v.iMargin = target;
				this.v.aMargin = this.v.iMargin - (this.v.visibleFirst * this.v.blockWidth) - this.v.center;
				this.dom.list.style.marginLeft = -this.v.aMargin + 'px';
			} else {
				this.v.iMargin = this.v.center;
			}
		}
		
		// скролл бар
		this.dom.scroll.style.marginLeft = Math.round( (this.v.sliderWidth / (this.v.arr.length * this.v.blockWidth)) * (this.v.iMargin - this.v.center) ) + 'px';
	},
	
	// Быстро показать
	showFast: function(target)
	{
		var side = this.v.iMargin - (target+this.v.center) < 0 ? 'right' : 'left';
		//document.getElementById('ssss').innerHTML = side;
		
		this.hideAll();
		this.v.iMargin = target+this.v.center;// < this.v.center ? this.v.center : target+this.v.center;
		
		
		var h = Math.floor(target / this.v.blockWidth); // количество скрытых блоков с начала
		var margin = target - (h * this.v.blockWidth);
		this.v.visibleFirst = h;

		this.v.last = this.v.center + (this.v.visibleFirst * this.v.blockWidth);
		
		for(i=0; i<=Math.ceil(this.v.blocksOnScreen*1.5); i++) {
			this.v.visibleLast = this.show(h, 'right');
			h++;
			/*if (side=='right') 
			{
				this.v.last -= this.v.blockWidth;
			}
			else
			{
				this.v.last += this.v.blockWidth;
			}*/
		}
		this.v.aMargin = margin;
		this.dom.list.style.marginLeft = -this.v.aMargin + 'px';

	},
	
	// скрыть все
	hideAll: function()
	{
		var block = 0;
		for (var i = 0; i < this.v.arrShownBlocks.length; i++) {
			var block = this.v.arrShownBlocks[i];
			document.getElementById('b'+ block ).style.display='none';
		}
		this.v.arrShownBlocks = [];
	},
	
	/**
	 * показать
	 */
	show: function(from, side)
	{
		var lastShow = from;
		if ( from >= 0 && from < this.v.blocksCount) {
			if (side == 'right')
				this.v.arrShownBlocks.push(from);
			else 
				this.v.arrShownBlocks.unshift(from);
			document.getElementById('b'+ from ).style.display = 'block';			
			document.getElementById('img-'+ from ).src = this.v.arr[from][2] + '/prew/' + this.v.arr[from][0];
			lastShow = from;
		}
		return lastShow;
	},
	
	/**
	 * скрываем лишнее
	 */
	hide: function(from, side)
	{
		var lastHidden = 0;
		if ( from >= 0 && from < this.v.blocksCount) {
			if (side=='right')
				this.v.arrShownBlocks.shift();
			else 
				this.v.arrShownBlocks.pop();
			document.getElementById('b'+ from ).style.display='none';
			lastHidden = from + 1;
		}
		return lastHidden;
	},
	
	/**
	 * Рассчитать ширину скролл-контейнера
	 */
	calcSliderWidth: function()
	{
		this.v.sliderWidth = Number(this.dom.slider.offsetWidth);
		qq = this.v.sliderWidth + 5;
		document.getElementById("arr-r").style.marginLeft = qq + 25 + "px";
	},
	
	// TODO: удалить
	elems: function()
	{
		document.getElementById('showblocks').innerHTML = '::';
		for (var i=0; i<this.v.arrShownBlocks.length; i++) {
			document.getElementById('showblocks').innerHTML += this.v.arrShownBlocks[i] +'; ';
		}
	}
};
