/*
jQuery 動畫擴充 
require $.fn.imgLoader
*/
;(function($){
	
    /*  Default options  */
    var defaults = {
		autoPlay : false,
        speed :	100,
        loop :	true
    };
	
	$.fn.imgAnimate = function(imgs, options)
	{
		var tm = null;
		var currentFrame = 0;
		var jq_mainImg = $('<img />').hide().appendTo(this);
		options = $.extend({}, defaults, options);
		// 依靠LoadEvent
		var imgLoadBox = null;
		var totalFrames = 0;
		
		var jq_self = $(this).css({
			'position':'relative'
		}).imgLoader(imgs, {
			complete : function(LoadEvent){
				imgLoadBox = LoadEvent.imgLoadBox;
				totalFrames = LoadEvent.total;
				jq_mainImg
				.show()
				.attr('src', imgLoadBox.find('img:eq(0)').attr('src'))
				;
				this.hide().show('slow', function(){
					if (options.autoPlay) {jq_self.play();}
				})
			},
			step : function(LoadEvent){
				LoadEvent.loadbar.text('Loading... ' + ((LoadEvent.loaded/LoadEvent.total) * 100 >> 0) + '%');
			}
		});
		
		jq_self = $.extend(jq_self, {
			pause : function()
			{
				if(tm){ clearTimeout(tm); }
				tm = null;
				return jq_self;
			},
			stop : function()
			{
				return jq_self.reset();
			},
			reset : function()
			{
				if(tm){ clearTimeout(tm); }
				tm = null;
				currentFrame = 0;
				if (imgLoadBox)
				{
					var src = imgLoadBox.find('img:eq(0)').attr('src')
					jq_mainImg.attr('src', src);
				}
				return jq_self;
			},
			play : function(){
				if (imgLoadBox)
				{
					if (tm) 
					{
						jq_self.reset();
					}
					tm = setInterval(function(){
						var src = imgLoadBox.find('img:eq('+currentFrame+')').attr('src')
						jq_mainImg.attr('src', src);
						currentFrame++;
						if (currentFrame >= totalFrames)
						{
							if (!options.loop)
							{
								jq_self.stop();
							}
							else
							{
								currentFrame = 0;
							}
						}
					}, options.speed);
					
				}
				return jq_self;
			}
		});
		return jq_self;
	};
	
		
})(jQuery);
