﻿// internet explorer not 'fading' in or out.  may need to add the following to relative positioned elements
// opacity:inherit;
//filter: inherit;
// #banners .banner * {
//     opacity:inherit;
//     filter:inherit;
// }


(function($) {
	$.fn.sltbanner = function(options) {
		var defaults = {
			interval: true, // move to another block on intervals.
			intervaltime: 5000, // interval time in milliseconds.
			animation: true, // false is instant, true is animate. (not implemented)
			duration: 1000 // how fast must the animation move in ms?
			//			content: $('#banners')
		};
		var options = $.extend(defaults, options);

		var hasThumbnails = $('.thumbnails', this).length > 0;
		var banners = (hasThumbnails ? $('.banners', this) : $(this));
		var thumbnails = (hasThumbnails ? $('.thumbnails', this) : undefined);
		//		var pages = $(this).children();

		var timerId;

		return this.each(function() {
			initEvents();
			move(0);
		});

		function initEvents() {
			$(thumbnails).children().each(function() {
				$(this).click(function(event) {
					var index = $(thumbnails).children().index($(this));
					move(index);
				});
			});
		}

		function setTimer() {
			if (options.interval) {
				clearTimeout(timerId);
				timerId = setTimeout(function() {

					var current = $('.selected', banners);
					var index = $(banners).children().index(current);
					if (index + 1 == $(banners).children().length) {
						move(0);
					} else {
						move(index + 1);
					}
				}, options.intervaltime);
			}
		}

		function move(index) {
			// update selected thumbnail
			if (hasThumbnails) {
				$('.selected', thumbnails).removeClass('selected');
				var newitem = $(thumbnails).children().get(index);
				$(newitem).addClass('selected');
			}

			if ($.support.opacity) {
				if ($('.selected', banners).length > 0) {
					// hide current item then show new item
					$('.selected', banners).fadeOut(options.duration, function() {
						$(this).removeClass('selected');
						var newitem = $('.banner', banners).get(index);
						$(newitem).fadeIn(options.duration, function() {
							$(this).addClass('selected');
						});
					});

				} else {
					// all items are currently hidden, just show new item
					var newitem = $('.banner', banners).get(index);
					$(newitem).fadeIn(options.duration, function() {
						$(this).addClass('selected');
					});
				}

			} else {
				if ($('.selected', banners).length > 0) {
					$('.selected', banners).removeClass('selected');
				}
				var newitem = $('.banner', banners).get(index);
				$(newitem).addClass('selected');
			}
			setTimer();
		}
	};
})(jQuery);
