/*
 * jQuery mouseGallerySlide v1.1.0
 *
 * Copyright (c) 2008 Taranets Aleksey
 * www: markup-javascript.com
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */

jQuery.fn.mouseGallerySlide = function(_options){
	// defaults options
	var _options = jQuery.extend({
		scrollElParent: 'ul',
		scrollEl: 'li'
	},_options);

	return this.each(function(){
		var _this = $(this),
			_gWidth = _this.outerWidth(),
			_scrollElParent = jQuery(_options.scrollElParent,_this),
			_scrollEl = jQuery(_options.scrollEl,_this),
			_liWidth = _scrollEl.outerWidth(true),
			_liSum = _scrollEl.length * _liWidth;

		var _sec = (_liSum - _gWidth) * 30,
			_maxMargin = _liSum,
			_posHolder = _this.offset(),
			_width = _this.outerWidth(),
			_height = _this.outerHeight();
			
		var _chapter = _gWidth/12,
			_speed = 0
			_direction = 2;
			_timerOut = false;
			
		var _cloneList = _scrollEl.clone();
		_scrollElParent.append(_cloneList);
		_scrollElParent

		jQuery(document).resize(function(){
			_posHolder = _this.offset();
		});

		$(document).mousemove(function(e){
			if (e.pageX > _posHolder.left && e.pageX < (_posHolder.left + _width) && e.pageY > _posHolder.top && e.pageY < (_posHolder.top + _height))
				mouseOverMove(e);
			else  {
				_scrollElParent.stop();
				_speed = 0;
			}
		});

		function mouseOverMove(e) {
			var _newSpeed = 0;
			for (var i=0; i <= 12; i++) {
				if ((_chapter*i) > (e.pageX - _posHolder.left)) {
					switch(i){
						case 1: _newSpeed = 4;break
						case 2:	_newSpeed = 3;break
						case 3: _newSpeed = 2;break
						case 4: _newSpeed = 1;break
						case 12: _newSpeed = 4;break
						case 11: _newSpeed = 3;break
						case 10: _newSpeed = 2;break
						case 9: _newSpeed = 1;break
						default:_newSpeed = 0;
					}
					if (i < 5) _direction = 1;
					else if (i > 8) _direction = 3;
					break;
				}
			}
			if(_speed != _newSpeed) {
				_speed = _newSpeed;
				_speed = _speed/10;
			    animateEl();
			}
		}
		function animateEl() {
			if (_timerOut) clearTimeout(_timerOut);
			_scrollElParent.stop();
			var _curMargin = parseInt(_scrollElParent.css('marginLeft'));
			if (_direction == 1) {
				var k = -_curMargin/_maxMargin;
				_scrollElParent.stop()
					.animate(
						{marginLeft:0},
						{easing:'linear',duration:(_sec/_speed)*k, complete:function(){
							_scrollElParent.css({'marginLeft':-(_maxMargin)});
							_timerOut = setTimeout(function(){animateEl()},15)
						}}
					);
			}
			if (_direction == 3) {
				var k = (_maxMargin + _curMargin)/_maxMargin;
				_scrollElParent.stop()
					.animate(
						{marginLeft:-_maxMargin},
						{easing:'linear',duration:(_sec/_speed)*k, complete:function(){
							_scrollElParent.css({'marginLeft':0});
							_timerOut = setTimeout(function(){animateEl()},15)
						}}
					);
			}
		}
	});
}




	
