(function($) {
	$.hoverScroll = {
		defaults: {
			fps: 30,
			centerRadius: '40%',
			maxSpeed: 300,
			minSpeed: 60,
			step: 128,
			acceleration: 5
		}
	},
	$.hoverScroll.go = function(e) {
		var hs = e.hoverScroll;
		var o = hs.opts;
		var v = o.vars;
		var pos = v.pos;
		var dt = o.delay/1000;
		var step = o.step;
		
		var cr = parseInt(o.centerRadius)/100;
		var sf = parseInt(o.sideFields)/100;
		
		if(v.phase<0) {
			v.phase=0;
			v.startX = e.scrollLeft;
		}
		var direction;
		if (pos<0.5) {
			direction = -1;
		} else if(pos>0.5) {
			direction = 1;
		} else {
			direction = 0;
		}
		var distance = step/2 - Math.abs((e.scrollLeft % step) - step/2);
		var sdistance = e.scrollWidth-e.offsetWidth-e.scrollLeft;
		if(sdistance < step/2) distance = sdistance;
		if(v.phase==2 && (direction==0 || distance==0)) {
			hs.stop();
			return;
		}
		
		if((e.scrollLeft < step/2 && direction==-1) || (sdistance < step/2 && direction==1)) {
			v.phase=2;
		}
		
		if(v.phase==0) {
			if(v.dX==0) {
				v.dX = direction*o.minSpeed;
			} else if(Math.abs(v.dX)>=o.maxSpeed) {
				v.dX = direction*o.maxSpeed;
				v.phase=1;
			} else {
				v.dX += direction*o.acceleration;
			}
		} else if(v.phase==1) {
			
		} else if(v.phase==2) {
			if(Math.abs(v.dX)>=o.minSpeed) {
				v.dX -= direction*o.acceleration;
			} else {
				v.dX = direction*o.minSpeed;
			}
		}
		v.dS += v.dX*dt;
		if(v.phase==0 && v.dS==0 || v.phase==2 && distance==1) v.dS=1*direction;
		if(Math.abs(v.dS) >= 1) {
			e.scrollLeft += v.dS;
			v.dS = 0;
		}
		
		v.tID = setTimeout(function() {$.hoverScroll.go(e)} , o.delay);
	};
	
	$.fn.hoverScroll = function(options) {
		var opts = $.extend({}, $.hoverScroll.defaults, options);
		
		opts.delay = 1000/opts.fps;
		opts.vars = {
			dX: 0,
			dS: 0,
			tID: -1,
			phase: -1,
			startX: 0
		}
		
		return this.each(function() {
			var $this = $(this);
			tID = 0;
			this.hoverScroll = {}
			this.hoverScroll.element = this;
			this.hoverScroll.opts = opts;
				
			this.hoverScroll.going = function() {
				return opts.vars.tID>=0;
			}
			this.hoverScroll.brake = function() {
				opts.vars.phase = 2;
			}
			this.hoverScroll.stop = function() {
				clearTimeout(opts.vars.tID);
				opts.vars.tID = -1;
				opts.vars.pos = 0.5;
				opts.vars.phase = -1;
				opts.vars.dX = 0;
			};
			this.hoverScroll.forward = function() {
				opts.vars.pos = 1;
				opts.vars.phase = 0;
				if(opts.vars.tID<=0) {
					$.hoverScroll.go(this.element);
				}
			};
			this.hoverScroll.backward = function() {
				opts.vars.pos = 0;
				opts.vars.phase = 0;
				if(opts.vars.tID<=0) {
					$.hoverScroll.go(this.element);
				}
			};
		})
		.css({overflow: 'hidden'});
	}
})(jQuery);


