/* 
HoverScroller (C) Oki Uimonen, Turning Point Oy
Use freely but don't remove this comment
*/
(function($){
$.hoverScroller = {};
	
$.hoverScroller.add = function(options) {
	$.hoverScroller.hoverScrollers.push(new $.hoverScroller.HoverScroller(options));
}	
		
$.hoverScroller.hoverScrollers = [];

$.hoverScroller.HoverScroller = function(options) {
	wrapperId = 'hs_wrapper_' + options['content'].substring(1);
	$(options['content']).wrap('<div id="'+ wrapperId +'"></div>');
	this._wrapper = $('#'+wrapperId);
	this._content = $(options['content']);
	
	this._wrapper.css({
		'position' : 'relative',
		'width' : options['width'],
		'height': options['height'],
		'overflow': 'hidden',
		'display' : 'block'
	});
	
	this._content.css({
		'position' : 'absolute',
		'top:' : '0px',
		'left' : '0px',
		'white-space' : 'nowrap',
		'display' : 'block'
	});
	
	this._wrapperWidth = this._wrapper.outerWidth(); 
	this._wrapperHeight = this._wrapper.outerHeight();
	this._contentWidth = this._content.outerWidth();
	this._contentHeight = this._content.outerHeight();		
	
	this._ratioX = (this._contentWidth - this._wrapperWidth) / this._wrapperWidth;
	this._ratioY = (this._contentHeight - this._wrapperHeight) / this._wrapperHeight;
	
	$('#status').html(this._contentWidth);
	if(this._ratioX < 0) this._ratioX = 0;
	if(this._ratioY < 0) this._ratioY = 0;		
	this._animSpeed = options['animSpeed'];

	this.bindEvent();
}

$.hoverScroller.HoverScroller.prototype = {	
	bindEvent : function() {
		that = this;
		
		this._wrapper.bind('mousemove', function(e) {
			for(sc in $.hoverScroller.hoverScrollers) {
				if($.hoverScroller.hoverScrollers[sc]._wrapper.attr('id') == e.currentTarget.id) {
					$.hoverScroller.hoverScrollers[sc].update(e.pageX,e.pageY);
				}
			}	
		});
	},
	
	update : function(pageX,pageY) {
		if(this._animActive) return;
		
		offset = $(this._wrapper).offset();
		mouseX = pageX - offset.left;
		mouseY = pageY - offset.top;
		
		// this._content.stop(true,true);
		pos = this._content.position();
		contentX = -pos.left;
		contentY = -pos.top;
		
		distance = Math.sqrt(Math.pow((mouseX*this._ratioX-contentX),2) + Math.pow((mouseY*this._ratioY-contentY),2));
		animDelay = parseInt(distance * this._animSpeed);
		
		
		if(distance > 75) {
			this._animActive = true;
			that = this;
			this._content.animate({ 
					'top' : parseInt(-mouseY * this._ratioY) + 'px',
					'left' : parseInt(-mouseX * this._ratioX) + 'px'
				}, animDelay, function() {
					that._animActive = false;
			});	
		}
		
		else {
			this._content.css({ 
			'top' : parseInt(-mouseY * this._ratioY) + 'px',
			'left' : parseInt(-mouseX * this._ratioX) + 'px'
			});
		}
			
		
		
			
	}
		
}
})(jQuery);

