
/*
 * AnimPics 
 * Copyright (c) 2010 Mirre Svea Jensen
 *
 * Dual licensed under the MIT and GPL licenses:
 * 	http://www.opensource.org/licenses/mit-license.php
 * 	http://www.gnu.org/licenses/gpl.html
 *
 */

;(function($)
{
	  
    $.fn.extend(
	{    
        AnimPics: function(opt) 
		{   
            var self = this;
   
            var defaults = 
			{   
				contentClass : '.subPic',
				indexHiddenFieldClass: '.animPicIndexField',
				animationSpeed: 2000,
				animationDelay: 5000,
				carusselIdentClass: '.carussel',
				height: 155
            }   
                   
            self.o =  $.extend(defaults, opt);  
			self.height(self.o.height).css('text-align', 'center');
			self.Init();
			
			self.StartAnimation();
			
			
		},
		
		Init: function ()
		{
			var self = this;
			self.InitElements();
			self.HideElemets(self.animIndex);
			self.Animate = true;
			var testElems = $(document).find(self.o.carusselIdentClass);
			if(testElems)
			{
				if(testElems.length > 0)
				{
					self.Animate = false;
				}
			}
		},
		
		InitElements: function()
		{
			var self = this;
			self.elems = $(this).find(self.o.contentClass);
			self.hidden = $(this).find('input' + self.o.indexHiddenFieldClass);
			self.animIndex = parseInt(self.hidden.val());
			self.Cnt = self.elems.length;
		},
		
		SetIndex: function(index)
		{
			var self = this;
			if(index >= self.Cnt)
				index = 0;
			self.animIndex = index;
			self.hidden.val(self.animIndex);
		},
		
		HideElemets: function (shownIndex)
		{
			var self = this;	
			self.elems.each(function(index, elem)
		 	{
				if(index != shownIndex)
				{
					$(elem).animate(
					{
						opacity: 0
					}, 0, function() {
					// Animation complete.
					});
				}
				$(elem)
				.css('z-index', (index + 1) * 100)
				.css('position', 'absolute');
				var posLeft = (self.width() - $(elem).width()) / 2;
				$(elem).css('margin-left', posLeft + 'px')
				.find('img').css('height', self.o.height + 'px');
		 	});
		},
		
		GetNext: function()
		{
			var self = this;
			var index = self.animIndex + 1;
			if(index >= self.Cnt)
				index = 0;
			return	$(self.elems[index]);
		},
		
		GetCurrent: function()
		{
			var self = this;
			return	$(self.elems[self.animIndex]);
		},
		
		StartAnimation: function()
		{
			var self = this;	
			if(self.Animate)
			{
				setTimeout(function()
				{
				self.AnimatePics();
				}, self.o.animationDelay);
			}
		},
		
		AnimatePics: function()
		{
			var self = this;
			self.GetNext().animate(
		   	{
				opacity: 1
		   	}, self.o.animationSpeed, function() {
    		// Animation complete.
  			});
			
			self.GetCurrent().animate(
		   	{
				opacity: 0
		   	}, self.animationSpeed, function() {
				self.SetIndex(self.animIndex + 1);
    		// Animation complete.
  			});
			
			self.StartAnimation();
		}
		
		

		  
    });   
       
})(jQuery);  
