 /* jQuery imageswitcher plugin
  * @author Julian Seiss <j.seiss@kernpunkt.de>
  * @version 1.1
  * @date June 21, 2011
  * @category jQuery plugin
  * @copyright (c) 2011 RheinEnergie AG
  */  
 (function($) {
	$.fn.extend({
		imageSwitcher: function(options)
		{
			var defaults =
			{
				transitionSpeed : 1000,
				displayTime : 6000,
				displayNavigationBar : 1
			};
			
			// Vars
			var options = $.extend(defaults, options);
			var obj = $(this);
			var itemCount = $('li', obj).length;
			var interval = null;
			var lock = false;
			
			// Create stage
			$(obj).append('<div id="stage"><div class="active"></div><div class="inactive"></div></div>');
			
			// Show first item
			$("#stage .active").html($(obj).find('li:first').html()).show("fade", options.transitionSpeed);
			
			// Create navigationbar
			if(options.displayNavigationBar)
			{
				// Add navigation container
				$(obj).after('<div id="switchernavigation"></div>');
				
				// Add navigation links
				for(i=0;i<=itemCount-1;i++)
				{
					$('#switchernavigation').append('<a class="navelement" ref="id_'+i+'"></a>');
				}
				$('#switchernavigation').append('<div class="clear></div>');
				$('#switchernavigation a:first').addClass('active');	

				// Click handler
				$('.navelement').click(function(e) {
					if(!lock && !$(this).hasClass('active'))
					{
						lock = true;
						window.clearInterval(interval);
						
						$('.navelement').removeClass('active');
						activate(parseInt($(this).attr('ref').split("_")[1]), $(this));
							
						// Avoid animation crossover
						window.setTimeout(function(){
							interval = window.setInterval(function() {
								autoSwitch();
							}, options.displayTime);
							lock = false;
						}
						, options.transitionSpeed + 500);
					}
					e.preventDefault();
				});
			}
			
			// Activate element by given index
			function activate(index, navelement)
			{
				$("#stage .inactive").html($(obj).find('li').eq(index).html()).show("fade", 0, function() {
					$("#stage .active").hide("fade", options.transitionSpeed, function() {
						$("#stage .inactive").removeClass('inactive').addClass('active');
						$(this).removeClass('active').addClass('inactive');
						$(navelement).addClass('active');
					});
				});
			}
			
			// Switch to next element
			function autoSwitch()
			{
				nextIndex = ($(".navelement.active").index()+1);
				if(nextIndex == itemCount)
					nextIndex = 0;
				
				$('.navelement[ref="id_'+nextIndex+'"]').trigger('click');
			}
			
			// Set interval
			interval = window.setInterval(function() {
				autoSwitch();
			}, options.displayTime);
    	}
	});
})(jQuery);	
