/*
 * Slider
 * @Author: Alexander Gavazov
 * @Copyrights: Alexander Gavazov
 * @Site: http://studio.bg
 */


var Slider = function(options) {
	this.target = $(options.target);
	this.stepWidth = options.stepWidth;
	this.stepsPerPage = options.stepsPerPage;
	this.stepsTotal = options.stepsTotal;
	this.linkPrev = $(options.linkPrev) || new Element('div');
	this.linkNext = $(options.linkNext) || new Element('div');

	this.duration = 90;
	this._pause = null;
	this._timmer = null;
	this._currentDirection = null;

	this.setBehaviour();
	this.move();
};

Slider.prototype.setBehaviour = function() {
	this.target.observe('mouseover', this.stop.bind(this));
	this.target.observe('mouseout', this.start.bind(this));

	this.linkPrev.observe('mouseover', this.move.bind(this, 'left'));
	this.linkNext.observe('mouseover', this.move.bind(this, 'right'));
};

Slider.prototype.move = function(direction) {
	if (direction) {
		this._currentDirection = direction;
	}

	if (!this._currentDirection) {
		this._currentDirection = 'left';
	}

	var leftPosition = (this._currentDirection == 'left') ? -(this.stepsTotal - this.stepsPerPage) * this.stepWidth : 0;

	clearTimeout(this._pause);
	clearTimeout(this._timmer);
	this._pause = setTimeout(this.doMove.bind(this, leftPosition), 500);
};

Slider.prototype.doMove = function(askedPosition) {
	var curentPosition = parseInt(this.target.style.left);

	if (isNaN(curentPosition)) {
		curentPosition = 0;
	}

	if (this._currentDirection == 'left' && askedPosition >= curentPosition) {
		this.move('right');
		return;
	} else if (this._currentDirection == 'right' && askedPosition <= curentPosition) {
		this.move('left');
		return;
	}

	this.target.style.left = (this._currentDirection == 'left' ? curentPosition - 1 : curentPosition + 1) + 'px';

	clearTimeout(this._timmer);
	this._timmer = setTimeout(this.doMove.bind(this, askedPosition), this.duration);
};

Slider.prototype.stop = function() {
	clearTimeout(this._pause);
	clearTimeout(this._timmer);
};

Slider.prototype.start = function() {
	this.move(this._currentDirection);
};
