//2013-09-06
(function( $ ){
	"use strict";

function sett0r(prop,val)
			{
				if(typeof(val)==="undefined")	
				{
					// get
					return this.data("IBEmc").settings[prop];
				}
				else
				{
					// set
					this.data("IBEmc").settings[prop]=val;
					return this;//seb .each(function() {});
				}
			}


	var methods = {
    	init : function( options ) 
		{
				/*
				settings:
					- startFrame
					- fileBegin
					- fileEnd
					- numBegin
					- numEnd
					* fps
					- minFrame
					- maxFrame
					
				options:
					- play
					- stop
					- currentFrame (get/set)
				*/
				var currentSettings = $.extend({startFrame:1,fps:25,playing:false,playAltDir:1,minFrame:undefined,maxFrame:undefined}, options);
				var $this = this;
				
				function persistent0r()
				{
					if(typeof $this.data("IBEmc") !== "undefined")
					{
						if(currentSettings!=="undefined")
						{
							for(var key in currentSettings)
							{
								var value = currentSettings[key];
								if(key=="startFrame") value = Number(value);
								$this.data("IBEmc").settings[key]=value;
							}
						}
					}
				}
							
					
				var data = $this.data('IBEmc');
				
				//If the plugin hasn't been initialized yet
				if ( ! data ) 
				{
					//debug console.log("1st init MC");
									
					//settings objekt wird erzeugt
					var settings={};
					$(this).data('IBEmc',{target : $this,settings : settings});
					
					// Eingaben werden dauerhaft gespeichert
					persistent0r();
				}
				
				// Nachträgliche Eingaben überschreiben bereits gespeicherte Daten
				persistent0r();
				
				
				//Bilder in Container laden
				var targetDiv=$('<div></<div>');
				$(this).append(targetDiv);
				// sequenz aus regelmaessigen dateinamen
				if(typeof $this.data("IBEmc").settings.numBegin !== "undefined")
				{
					var intBegin=Number($this.data("IBEmc").settings.numBegin);
					var intEnd=Number($this.data("IBEmc").settings.numEnd);
					for(var i=intBegin;i<=intEnd;i++)
					{
						var counter=String(i);
						while(counter.length<String($this.data("IBEmc").settings.numEnd).length) counter="0"+counter;
						var img= new Image;
						var pathStart=$this.data("IBEmc").settings.fileBegin;
						var pathEnd=$this.data("IBEmc").settings.fileEnd;
						img.src=pathStart+counter+pathEnd;
						//$(img).css({position:'absolute',left:'0px',top:'0px'}).hide();
						$(img).css({position:'absolute',left:'0px',top:'0px',opacity:0});
						$(img).attr("draggable", "false");
						targetDiv.append(img);
					}
				}				
				// pfade manuel per array (wird nur beruecksichtigt, wenn numBegin und co. nicht definiert sind)
				else if(typeof $this.data("IBEmc").settings.images!=="undefined")
				{
					var imageArray;
					if (typeof $this.data("IBEmc").settings.images ==="string")
					{
						imageArray=$this.data("IBEmc").settings.images.split(',');
					}
					else imageArray=$this.data("IBEmc").settings.images;
					for(var i=0; i<imageArray.length;i++)
					{
						var img = new Image;
						img.src=imageArray[i];
						//$(img).css({position:'absolute',left:'0px',top:'0px'}).hide();
						$(img).css({position:'absolute',left:'0px',top:'0px',opacity:0});
						$(img).attr("draggable", "false");
						targetDiv.append(img);
					}
				}
				else { 
					//seb FIXME TODO   throw ?
					//seb console.log("keine Bilder angegeben");
					console.error("keine Bilder angegeben");
				}
				$(this.children().children('img')[$this.data("IBEmc").settings.startFrame-1]).css('opacity',1);
				$this.data("IBEmc").settings.currentFrame=$this.data("IBEmc").settings.startFrame;
				// Plugin kann kaskadiert (?) werden
				return this;//seb .each(function(){});
				

		},
	

		destroy : function( )
		{
			return this.each(function()
			{
				var $this = $(this);
				var data = $this.data('IBEmc');
		
				// Namespacing FTW
				$(window).unbind('.IBEmc');
				$this.removeData('IBEmc');
			})

		},
		
		play : function(val)
		{
			if(typeof(val)==="undefined") this.data("IBEmc").settings.playdir='forward'
			else this.data("IBEmc").settings.playdir=val;
			
			
			function mod(n,k)
			{
				if(n%k==0) return k
				else return (n%k)
			}
			
			var tf;
			if(typeof this.data("IBEmc").settings.numBegin!=="undefined") tf=Number(this.data("IBEmc").settings.numEnd)-Number(this.data("IBEmc").settings.numBegin)+1
			else if(typeof this.data("IBEmc").settings.images!=="undefined") tf=this.data("IBEmc").settings.images.length;

			function loop($this)
			{
				if($this.data("IBEmc").settings.playing)
				{
					var dir=$this.data("IBEmc").settings.playdir;
					var nextFrame;
					
					if(dir=='forward')
					{
						nextFrame=mod($this.data("IBEmc").settings.currentFrame+1,tf);
					}
					else if(dir=='backward')
					{
						nextFrame=mod($this.data("IBEmc").settings.currentFrame-1,tf);	
					}
					else if(dir=='random')
					{
						nextFrame=Math.floor(tf*Math.random()+1);
						if(nextFrame>tf) nextFrame=tf;
					}
					else if(dir=='alternate')
					{
						var _dir=$this.data("IBEmc").settings.playAltDir;
						var _cf=$this.data("IBEmc").settings.currentFrame;
						if(_dir==1)
						{
							//forward
							if(_cf<tf) 	nextFrame=$this.data("IBEmc").settings.currentFrame+1;
							else
							{
								nextFrame=$this.data("IBEmc").settings.currentFrame-1;
								$this.data("IBEmc").settings.playAltDir=-1;
							}
						}
						else
						{
							if(_cf>1) nextFrame=$this.data("IBEmc").settings.currentFrame-1;
							else
							{
								nextFrame=$this.data("IBEmc").settings.currentFrame+1;
								$this.data("IBEmc").settings.playAltDir=1;											
							}
						}
					}
					
					
					$this.IBEmc('currentFrame',nextFrame);
					setTimeout(function(){loop($this);},1000/$this.data("IBEmc").settings.fps);
				}
			}
			if(!this.data("IBEmc").settings.playing)
			{
				sett0r.call(this, 'playing',true);
				loop(this);
			}
			
			return this;//seb .each(function(){});

		},
		
		stop : function()
		{
				sett0r.call(this, 'playing',false);
		},

		currentFrame : function(val)
		{
			var 
			minFrame = this.data("IBEmc").settings.minFrame,
			maxFrame = this.data("IBEmc").settings.maxFrame;
			
			if(minFrame !== undefined && val < minFrame) return;
			if(maxFrame !== undefined && val > maxFrame) return;

			
			if(typeof(val)!=="undefined")
			{	
				$(this).children().children('img').css('opacity',0);
				$($(this).children().children()[val-1]).css('opacity',1);
			}
			return sett0r.call(this, 'currentFrame',val);//Number!!!
		},
		
		fps : function(val)
		{
				return sett0r.call(this, 'fps',val);
		},
	
  };

  $.fn.IBEmc = function( method ) {
    
    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.IBEmc' );
    }    
  
  };

})( jQuery );
