/**
 * @author dave
 */

(function($) {
	$.fn.bluntSlideshow = function(settings){
		
		var config = {
			target			 : null,
			speed			 : 3000 //miliseconds
		};
		
		if (settings) $.extend(config, settings);
		
		var C=config;
		var self=$(this);
		var target=C.target;
		var _srcs = new Array();
		var _indx = 0;
		var _state = false;
		var tw;
		
		var $Above,$Below;
		var easeFuncUp = Tween.strongEaseIn;
		var easeFuncDown = Tween.strongEaseIn;
		var tweenTime = 3;
		var delayTime = 4000;
		var listLen = 0;
		
		var tid = null; 

		init();
		
		function init() { 
			self.each(function(i, el) { 
				_srcs.push($(el).attr('src'));			
			});			
			
			createPlaceHolders();
			
			listLen = _srcs.length -1;
			_indx = 0; 
			
			loadFirstImage();
			nextImage();
		}
		
		function createPlaceHolders() { 
			target.append('<div id="Below"></div><div id="Above"></div>');
			
			$Above=$('#Above');
			$Below=$('#Below');
			
			$Below.css({ 
				'position'	: 'absolute',
				'top'		: 0,
				left 		: 0, 
				width		: '100%', 
				height		: '100%', 
				background 	: 'none',
				'z-index'	: 10

			});
			
			$Above.css({ 
				position	: 'absolute',
				top			: 0,
				left 		: 0, 
				width		: '100%', 
				height		: '100%', 
				background 	: 'none',
				'z-index'	: 20
				
			});

		}
		
		function loadFirstImage() {
			_indx = randomStart();
			$Above.append(getImgTag(_srcs[_indx]));	
			_indx++;
			_state=true;	
		}
		
		function nextImage() { 
		
			tw = null;
			
			if(_state) { 
				below();
				_state=false;
			} else { 
				above();
				_state=true;
			}
		}
		
		function below() { 
			$Below.find('img').remove();
			$Below.append(getImgTag(_srcs[_indx]));	
			
			clearTimeout(tid);
			tid = window.setTimeout(fadeDown,delayTime);
		}
		
		function above() { 
			$Above.find('img').remove();
			$Above.append(getImgTag(_srcs[_indx]));	
			
			clearTimeout(tid);
			tid = window.setTimeout(fadeUp,delayTime);
		}
		
		function fadeUp() { 
			tw=new OpacityTween($Above[0],easeFuncUp,0,100,tweenTime);
			tw.onMotionFinished = function(e) { tweenComplete(e); };
			tw.start();		
		}
		
		function fadeDown() { 
			tw=new OpacityTween($Above[0],easeFuncDown,100,0,tweenTime);
			tw.onMotionFinished = function(e) { tweenComplete(e); };
			tw.start();
		}
		
		
		function tweenComplete(e) { 
			var t = e.target;
			//console.log('ll : '+listLen+', _indx : '+_indx);

			(_indx >= listLen ) ? _indx = 0 : _indx++;
			
			nextImage();
		}
		
		
		function getImgTag(imgSrc) { 
			return '<img src="'+imgSrc+'" />';
		} 
		
		//function to get random number upto m
		function randomStart()	{
  			return Math.round((Math.random()*listLen));
		}

	}

})(jQuery);

