/**
 * Imagegallery plugin for jQuery
 * @copyright SABIO GmbH, Hamburg
 * @author S. Luensdorf
 * @created 02/05/2010
 */
(function ($) {
	var window = this;
	
	$.fn.SabioGallery = function (settings) {
		var settings = $.extend({}, $.fn.SabioGallery.defaults, settings);
		var container = $(this);
		var items = $(settings.itemSelector, container);
		var controls = $(document.createElement('div')).addClass('galleryControls');
		var link = $(document.createElement('span')).addClass('galleryLink');
		var current = $(items[settings.firstItem]);
		var timer;
		
		// define function to show items
		var showItem = function (item) {
			var prepareNextItem = function () {
				if (!settings.autoPlay) {
					return;
				}
				
				var nextItem = (current.next().length > 0) ? current.next() : $(items[0]);
				
				window.clearTimeout(timer);
				timer = window.setTimeout(function () {
					showItem(nextItem);
				}, settings.interval);
			};
			
			var showNextItem = function () {
				current = item;
				current.fadeIn(settings.fading, prepareNextItem);
				markActiveItem(current);
			};
			
			var markActiveItem = function (item) {
				var index = -1;
				
				for (var i = 0, l = items.length; i < l; i++) {
					if (item[0] == items[i]) {
						index = i;
					}
				}
				controls.children().removeClass('active').eq(index).addClass('active');
			};
			
			if (current === item) {
				prepareNextItem();
			}
			else if (!!current) {
				current.fadeOut(settings.fading, showNextItem);
			} else {
				showNextItem();
			}
		};
		
		// add wrapper and css class to container
		container.wrap('<div class="sabioImageGallery"/>');
		container.addClass('galleryContainer');
		
		// add links to control container and append controls
		for (var i = 0, l = items.length; i <l; i++) {
			var item = $(items[i]);
			
			link.clone(false).attr('galleryItem', i).click(function (e) {
				var nextItem;
				var links = $('.galleryLink', controls);
				
				if (!!timer) {
					window.clearTimeout(timer);
				}
				
				for (var i = 0, l = links.length; i < l; i++) {
					if (this == links[i]) {
						nextItem = (!!items[i]) ? $(items[i]) : $(items[0]);
					}
				}
				showItem(nextItem);
			}).text(i + 1).appendTo(controls);
			
			if (i !== settings.firstItem) {
				item.hide();
			} else {
				item.show();
				controls.children().eq(i).addClass('active');
			}
		}
		controls.insertAfter(container);
		controls.wrap('<div class="controlsWrapper"/>');
		
		// set autoplay
		if (!!settings.autoPlay) {
			showItem(current);
		}
	};

	/**
	 * Default plugin configuration.
	 */
	$.fn.SabioGallery.defaults = {
		itemSelector: 'div.galleryItem',
		firstItem: 0,
		autoPlay: true,
		interval: 7000,
		fading: 200
	};
}).call(window, jQuery);