/* ************************ JQUERY CROSS EFFECT **************************** */

(function($){
	
	$.fn.crossEffect = function(options){
		
		var opts = $.extend({}, $.fn.crossEffect.defaults, options);
		
		return this.each(function(){
			
			// Cache the UL //
			var $this = $(this);
			
			var $next = $(opts.nextElement);
			
			// If it should be run on load of document //
			if(opts.runOnLoad){
				// If it should be delayed //
				if(opts.delayOnLoad){
					$.doTimeout('delay', opts.delayOnLoad , function(){	
						runEffect( $this, $next );
					});
				} else {
					runEffect( $this, $next );	
				}
			}
			if(opts.listeners){
				if(opts.listeners.length > 0){
					
					for(var x in opts.listeners){
						
						var list = opts.listeners[x];
						var z=0;
						var $obj;
						var eventType;
						var onEvent = false;
						
						for(var y in list){
							if(z == 0){
								$obj = $(y);
								eventType = list[y];
							} else {
								onEvent = list[y];
							}
							z++;
						}
						
						$obj.bind( eventType, function(event){
							if(onEvent){
								var onEffect = onEvent( $(event.target), event );
							}
							
							runEffect( $this, $next, function(){
								if(onEffect){
									onEffect();
								}
							});
						});
					}
			}
			}
		});
		
		function runEffect( $this, $next, callBack ){
			
			// If we're preventing an animation //
			if(opts.preventAnimation){
				$this.hide();
				$next.show();
				$next.css({
					opacity:1
				});
				return true;
			}
			
			switch(opts.animateMethod){
				case 'fade' :
					runCrossFade( $this, $next, callBack );
					break;
				case 'slide' :
					crossSlide( $this, $next, callBack );
					break;
			}
		}
		
		// For cross sliding two elements //
		function crossSlide( $this, $next ){
			
			switch(opts.animateType){
				case 'outIn':
					$this.slideUp( opts.animateSpeed );
					$next.slideDown( opts.animateSpeed );
					break;
				case 'over':
					$next.hide();
					$this.remove( opts.animateSpeed );
					$next.before( $this );
					$next.slideDown( opts.animateSpeed );
					break;
			}
			
		}
		
		// For cross fading two elements //
		function runCrossFade($this, $next, onComplete){
			switch(opts.animateType){
				case 'outIn':
					$this.animate({
						opacity:0
					}, opts.animateSpeed, onComplete );
					
					$next.animate({
						opacity:1
					}, opts.animateSpeed, onComplete );	
					break;
					
				case 'over':
					
					// Switch content order after hiding last image with opacity //
					$next.css({
						opacity:0		  
					});
					
					$this.remove();
					$next.before( $this );
					
					$next.animate({
						opacity:1
					}, opts.animateSpeed, onComplete );
					
					break;
			}	
		}
	}
	
	// Menu default options //
	$.fn.crossEffect.defaults = {
		delayOnLoad:2000,
		animate:true,
		animateMethod:'fade',
		animateSpeed:500,
		runOnLoad:true,
		fadeMethod:'fadeInOut'
	};
	
	
})(jQuery);
