/* 
* --__(CUSTOMATE)__--
*
* Allows you to move an HTML Object by making it follow a predefined path.
*
*
* VERSION: 1.0 LAST UPDATE: 06.12.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($) {		  
    $.fn.customate = function(options) 
	{
		var defaults = {
			moves: new Array,
			repeat: false,
			x_init: null,
			y_init: null,
			speed: 5000,
			gotofirstpos: false,
			img_left: null,
			img_right: null,
			zindex: 1
		};			

		//Init
		var opts = $.extend(defaults, options);	
		var obj = $(this);			
		var position_first = obj.position();
		var num_moves = 0;
		var nb_moves = opts.moves.length-1;
		var move = true;
		obj.css('position', 'absolute');
		obj.css('z-index', opts.zindex);
		
		if(opts.x_init == null) { opts.x_init = position_first.top; }
		if(opts.y_init == null) { opts.x_init = position_first.left; }
		
		obj.css('left', opts.y_init); 
		obj.css('top', opts.x_init); 
		
		
		/*
		* Reset position of the object
		*/
		function reset_to_first_position(next)
		{
			obj.animate({
				left: 	opts.y_init,
				top: 	opts.x_init,
			}, opts.speed, function() {
				if(next)
				{
					move = true;				
					movement();
				}
			});
		}
		
		/*
		*	Controls the movement of the object
		*/		
		function movement()
		{
			//Manage src
			if(opts.moves[num_moves][0] > 0 && opts.img_right != null)
			{
				obj.attr('src', opts.img_right);
			}
			else if(opts.moves[num_moves][0] <= 0 && opts.img_left != null)
			{
				obj.attr('src', opts.img_left);
			}
				
			obj.animate({
				left: 	'+='+opts.moves[num_moves][0],
				top: 	'+='+opts.moves[num_moves][1],
			}, opts.speed, function() {
				num_moves++;
				
				if(move)
				{
					if(num_moves > nb_moves)
					{
						num_moves = 0;
						if(opts.gotofirstpos)
						{
							reset_to_first_position(opts.repeat);
						}
						else if(opts.repeat)
						{
							movement();
						}
						else
						{
							move = false;
						}
					}
					else
					{
						movement();
					}
				}
			});
		}
		
		movement(opts.moves);
		
	};
})(jQuery);

























