// VERSION: 1.0 LAST UPDATE: 19.03.2011
/* 
 * Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 * 
 * Made by Tommy Thierry, tommy.thierry@gmail.com, Montreal, QC
 * Website: http://www.tom-art.ca/
 */
(function($) {		  
    // Fonction Random Move
    $.fn.randomMove = function(options) 
	{
		var defaults = {
			vitesseCroisiere : 60,
			directionX : 'right',
			directionY : 'down', 
			
			zIndex : 5,
			
			playground: 'body',
			
			heightBall : $(this).height(),
			widthBall : $(this).width(),			
			
			moreHeight : 0, 
			moreWidth : 0,
			
			ballX : null,
			ballY : null,
			
			onHover : false,
			onHoverFunction: function() {},
			onOutFunction: function() {}
		};			

		var opts = $.extend(defaults, options); 		
		var playVar = true;
				
		//Init info
		var heightPlayground = $(opts.playground).height();
		var widthPlayground = $(opts.playground).width();
		
		var PlaygroundPos = $(opts.playground).position();
		var XMin = PlaygroundPos.left;
		var YMin = PlaygroundPos.top;
		
		var HeightBallMax = YMin + heightPlayground - opts.heightBall + opts.moreHeight;
		var WidthBallMax = XMin + widthPlayground - opts.widthBall + opts.moreWidth;
		
		if(opts.ballX == null) opts.ballX = XMin + Math.floor(Math.random()*(WidthBallMax-XMin)); 
		if(opts.ballY == null) opts.ballY = YMin + Math.floor(Math.random()*(HeightBallMax-YMin)); 
		
		var directionX = opts.directionX;
		var directionY = opts.directionY;
		
		//Init Ball
		$(this).css('position', 'absolute');
		$(this).css('left', opts.ballX);
		$(this).css('top', opts.ballY);
		$(this).css('z-index', opts.zIndex);
		
		if(opts.onHover) { $(this).css('cursor', 'pointer'); }
		
		//Function
		function play(object)
		{
			if(playVar) moveBall(object);
		}
		
		function moveBall(object)
		{
			var ballX = $(object).css('left');
			var ballY = $(object).css('top');
			
			ballX = ballX.replace('px', '');
			ballY = ballY.replace('px', '');
			
			
			//On verifie si on a atteind la limit X et Y
			if (ballX >= WidthBallMax) directionX = 'left';
			else if (ballX <= XMin) directionX = 'right';
			
			if (ballY >= HeightBallMax) directionY = 'up';
			else if (ballY <= YMin) directionY = 'down';
			
			if(directionX == 'right') MoveX = '+=10';
			else MoveX = '-=10';
			if(directionY == 'down') MoveY = '+=10';
			else MoveY = '-=10';
			
			$(object).animate({
				left: MoveX,
				top: MoveY
			}, opts.vitesseCroisiere, function() {
				play(this);
		  	});
		}
		
		if(opts.onHover)
		{
			$(this).hover(
			  function () {
				opts.onHoverFunction();
				playVar = false;				
			  },
			  function () {
				playVar = true;
				opts.onOutFunction();
				play(this);
			  }
			);	
		}
		
		
		//On lance le move
		play(this);
		
		return $(this); 
	};
})(jQuery);
