jQuery(function($) {

	$.fn.followMouse = function(options)
	{
		var mouseX; // "global" mouse position on x-axis
		var mouseY; // "global" mouse position on y-axis
		
		// loop over all box elements...
		this.each(function(){
			
			var $box = $(this);	// create jquery box element with this
			var boxWidth = $box.width(); // width of box
			var boxHeight = $box.height(); // height of box

			// get all children elements in box (img, div, ...)
			var $elements = $box.children();
			
			var interval; // interval object
			
			// start interval on mouse enter (event handler applied to all boxes)
			$box.bind('mouseenter', function(event)
			{
			    if(interval)
			    {
			        window.clearInterval(interval);
			    }
				interval = window.setInterval(animate, 25); // =~ 25fps
			});
			
			// stop interval on mouse leave (event handler applied to all boxes)
			$box.bind('mouseleave', function(event)
			{
				window.clearInterval(interval);
			});			
			
			// trigger mouse tracking during mouse movement (event handler applied to all boxes)
			$box.bind('mousemove', function(event){
				// track mouse position (relative to document)
				mouseX = event.clientX;
				mouseY = event.clientY;
			});	
			
			// animation method 
			function animate()
			{
				var boxOffset = $box.offset(); // fetch box offset (relative to document)				
				
				// loop over all child elements
				$elements.each(function(i, element){
					$element = $(element); // create jquery element with element

					// read moveX and moveY attribute from element
					var moveX = $element.attr('moveX');
					var moveY = $element.attr('moveY');				

					// if moveX ...
					if(moveX && moveX != 0)
					{
						// calculate X-axis movement (relative to box)
						var marginX = Math.round((moveX / boxWidth) * (mouseX - boxOffset.left));
						// console.log(marginX);
						// update marginLeft
						$element.css('marginLeft',  marginX + 'px');	
					}

					// if moveY ...
					if(moveY && moveY != 0)
					{
						// calculate Y-axis movement (relative to box)						
						var marginY = Math.round((moveY / boxHeight) * (mouseY - boxOffset.top));

						// update marginTop
						$element.css('marginTop',  marginY + 'px');
					}
				});
			}				
		});
	}	
});
