/**
 * NetvMediaSlider
 * @author Christoph Dubach
 * @version 1.4
 */

jQuery.fn.NetvMediaSlider = function(settings) {
	settings = jQuery.extend(
	{
		slide_width: 612,           /* width of a single slide */
		slide_height: 416,          /* height of a single slide */
		displayduration: 0.8,		/* how many seconds is a slide visible */
		autoplay: true,				/* true | false */
		randomstart: false,			/* true | false */
		controls: true,				/* true | false */
		transitiontype: 'none',		/* none | slide | fade | crossfade */
		transitiontime: 0.6,		/* duration of transition in seconds; only relevant if transitiontype is slide or fade */
		fadebgcolor: '#000000',		/* against what color will be faded; only relevant if transitiontype is crossfade */
		label_forward: 'next',		/* title of the forward link */
		label_backward: 'previous'	/* title of the backward link */
	}, settings);
	
	return this.each(function()
	{
		var slideShowTimer;
		var slideShowActive;
		var slideShowPaused;
		var slideShowReadyToMove;
		var isTouchDevice;
		
		var totalItems = 0;
		var itemWidth = 0;
		var itemHeight = 0;
		var galleryWidth = 0;
		var movingDistance = 0;
		var animated = false;
		var $gallery = $j(this);
		var $navigation;
		
		var currentItem = 0;
		var previousItem;
		var nextItem;
		
		var processSlide = function(caller)
		{
			slideShowReadyToMove = false;
			clearTimeout(slideShowTimer);
			
			if (slideShowActive)
			{
				slideShowTimer = setTimeout(readyToMove, settings.displayduration * 1000);
			}
		}
		
		var formatGallery = function()
		{
			$gallery.find('li:first').css('display','block');
			itemWidth = settings.slide_width ? settings.slide_width : $gallery.find('li:first').css('position','absolute').width();
			itemHeight = settings.slide_height ? settings.slide_height : $gallery.find('li:first').height();
			
			galleryWidth = itemWidth;
			movingDistance = itemWidth;
			
			var bgColor = (settings.transitiontype == 'crossfade') ? settings.fadebgcolor : 'transparent';
			
			$gallery.css(
			{
				'width': galleryWidth,
				'height': itemHeight,
				'overflow': 'hidden',
				'position': 'relative',
				'background-color': bgColor,
				'clear': 'left'
			});
			$gallery.find('li').each(function(i)
			{
				$j(this).css(
				{
					'position': 'absolute',
					'top': 0,
					'left': 0,
					'display': 'none'
				});
				
				if (i == currentItem)
				{
					$j(this).show();
				}
				
				$j(this).data('itemId', i);
			});
		}
		
		var applyNavigation = function() {
			var navElement = '';
				navElement += '<div class="mediaslider-navigation">';
				navElement += '<a class="mediaslider-navigation-previous" href="#" title="'+settings.label_backward+'" onclick="return false"><span>'+settings.label_backward+'</span></a>';
				navElement += '<a class="mediaslider-navigation-next" href="#" title="'+settings.label_forward+'" onclick="return false"><span>'+settings.label_forward+'</span></a>';
				navElement += '</div>';
	
				$gallery.after(navElement);
	
				// Adjust the nav to the gallery width
				$navigation = $gallery.parent('div.mediaslider-container:first').find('div.mediaslider-navigation');
				$navigation.width(galleryWidth);
	
				// Apply the functions
				$navigation.find('a.mediaslider-navigation-previous').bind('click',function()
				{
					slideShowActive = false;
					moveBackward(this);
					
					if (isTouchDevice)
					{
						$navigation.parent().trigger('click');
					}
					
					return false;
				});
				$navigation.find('a.mediaslider-navigation-next').bind('click',function()
				{
					slideShowActive = false;
					moveForward(this);
					
					if (isTouchDevice)
					{
						$navigation.parent().trigger('click');
					}
					
					return false;
				});
				
				// Apply show/hide functions
				$gallery.parent('div.mediaslider-container:first').bind('mouseenter',function()
				{
					slideShowPaused = true;
					$navigation.show();
					return false;
				});
				$gallery.parent('div.mediaslider-container:first').bind('mouseleave',function()
				{
					slideShowPaused = false;
					$navigation.hide();
					if (slideShowActive)
					{
						moveForward(this);
					}
					return false;
				});
				
				if (isTouchDevice)
				{
					$gallery.parent('div.mediaslider-container:first').unbind('mouseenter').unbind('mouseleave').toggle(function()
					{
						slideShowPaused = true;
						$navigation.show();
						return false;
					}, function()
					{
						slideShowPaused = false;
						$navigation.hide();
						return false;
					});
				}
		}

		var moveForward = function(caller)
		{
			// Don't start animation if there's already an animation in progress, the button is disabled or a running slideshow is not ready
			if (animated || $j(caller).hasClass('disabled') || (slideShowActive && !slideShowReadyToMove)) return;
			
			animated = true;
			
			nextItem = (currentItem >= (totalItems - 1)) ? 0 : (currentItem + 1);
			
			$gallery.find('li').each(function(i)
			{
				// Hide current item
				if ($j(this).data('itemId') == currentItem)
				{
					$j(this).css('left', 0);
					if (settings.transitiontype == 'slide')
					{
						$j(this).animate({'left': -itemWidth }, settings.transitiontime*1000, function()
						{
							$j(this).hide();
						});
					}
					else if (settings.transitiontype == 'crossfade')
					{
						$j(this).fadeOut(settings.transitiontime*1000, 'linear', function()
						{
							animated = false;
						});
					}
					else if (settings.transitiontype == 'fade')
					{
						$j(this).css('z-index', totalItems-1);
						$j(this).delay(settings.transitiontime*1000).fadeOut(settings.transitiontime*950, 'linear', function()
						{
							animated = false;
						});
					}
					else
					{
						$j(this).hide();
					}
				}
				
				// Show next item
				if ($j(this).data('itemId') == nextItem)
				{
					if (settings.transitiontype == 'slide')
					{
						$j(this).css('left', itemWidth);
					}
					if (settings.transitiontype != 'fade' && settings.transitiontype != 'crossfade')
					{
						$j(this).show();
					}
					if (settings.transitiontype == 'slide')
					{
						$j(this).animate({'left': 0 }, settings.transitiontime*1000, function()
						{
							animated = false;
							processSlide($j(this));
						});
					}
					else if (settings.transitiontype == 'fade' || settings.transitiontype == 'crossfade')
					{
						var delay = 0;
						var delayTimer = null;
						if (settings.transitiontype == 'fade')
						{
							$j(this).css('z-index', totalItems);
							delay = settings.transitiontime*1000;
						}
						
						$j(this).fadeIn(settings.transitiontime*1000, 'linear', function()
						{
							delayTimer = setTimeout(function() { processSlide($j(this)); }, delay);
						});
					}
					else
					{
						animated = false;
						processSlide($j(this));
					}
				}
			});
			currentItem = nextItem;
		}
		
		var moveBackward = function(caller)
		{
			// Don't start animation if there's already an animation in progress, the button is disabled or a running slideshow is not ready
			if (animated || $j(caller).hasClass('disabled') || (slideShowActive && !slideShowReadyToMove)) return;
						
			animated = true;
			
			previousItem = (currentItem <= 0) ? (totalItems - 1) : (currentItem - 1);
			
			$gallery.find('li').each(function(i)
			{
				// Hide current item
				if ($j(this).data('itemId') == currentItem)
				{
					$j(this).css('left', 0);
					if (settings.transitiontype == 'slide')
					{
						$j(this).animate({'left': itemWidth }, settings.transitiontime*1000, function()
						{
							$j(this).hide();
						});
					}
					else if (settings.transitiontype == 'crossfade')
					{
						$j(this).fadeOut(settings.transitiontime*1000, 'linear', function()
						{
							animated = false;
						});
					}
					else if (settings.transitiontype == 'fade')
					{
						$j(this).css('z-index', totalItems-1);
						$j(this).delay(settings.transitiontime*1000).fadeOut(settings.transitiontime*950, 'linear', function()
						{
							animated = false;
						});
					}
					else
					{
						$j(this).hide();
					}
				}
				
				// Show previous item
				if ($j(this).data('itemId') == previousItem)
				{
					if (settings.transitiontype == 'slide')
					{
						$j(this).css('left', -itemWidth);
					}
					if (settings.transitiontype != 'fade' && settings.transitiontype != 'crossfade')
					{
						$j(this).show();
					}
					if (settings.transitiontype == 'slide')
					{
						$j(this).animate({'left': 0 }, settings.transitiontime*1000, function()
						{
							animated = false;
							processSlide($j(this));
						});
					}
					else if (settings.transitiontype == 'fade' || settings.transitiontype == 'crossfade')
					{
						var delay = 0;
						var delayTimer = null;
						if (settings.transitiontype == 'fade')
						{
							$j(this).css('z-index', totalItems);
							delay = settings.transitiontime*2000;
						}
						$j(this).fadeIn(settings.transitiontime*1000, 'linear', function()
						{
							delayTimer = setTimeout(function() { processSlide($j(this)); }, delay);
						});
					}
					else
					{
						animated = false;
						processSlide($j(this));
					}
				}
			});
			currentItem = previousItem;
		}
		
		var readyToMove = function(caller)
		{
			clearTimeout(slideShowTimer);
			slideShowReadyToMove = true;
			
			if (slideShowActive && !slideShowPaused)
			{
				moveForward();
			}
		}
		
		
		/*  INIT  */
		
		// Make items visible (they are invisible for <noscript> functionality)
		$gallery.show();
		
		totalItems = $j(this).find('li').size();
		
		// Set first slide to show
		if (settings.randomstart)
		{
			currentItem = Math.floor(Math.random() * totalItems);
		}
		
		// If transition type is 'none', transition time is 0
		if (settings.transitiontype != 'slide' && settings.transitiontype != 'fade' && settings.transitiontype != 'crossfade')
		{
			settings.transitiontype = 'none';
			settings.transitiontime = 0;
		}
			
		// Format the gallery properly
		formatGallery();
		
		// Check if we need the gallery functionality
		if (totalItems > 1)
		{	
			// Detect touch support of the browser
			isTouchDevice = ("ontouchend" in document);
			
			// Build and display the nav
			if (settings.controls)
			{
				applyNavigation();
			}
			
			// Allow external control
			$j(this).data(
			{
				showNextSlide:moveForward,
				showPreviousSlide:moveBackward,
				readyToMove:readyToMove
			});
		
			slideShowActive = settings.autoplay;
		}
			
		// Process first slide
		processSlide($j(this).find('li:first'));
	});
}
