﻿(function ($) {

	// Default configuration properties
	var defaults = {
		height: 118,
		speed: 8000
	};

	$.fn.teaserRotator = function (o) {
		return this.each(function () {
			new $.teaserRotator(this, o);
		});
	};

	$.teaserRotator = function (e, o) {
		this.options = $.extend({}, defaults, o || {});
		this.container = $(e);
		this.timer = null;

		// Add active class, and if it contains only 1 item then end the slideshow
		if ($(e).addClass("ActivatedTeaserRotator").find("li").length <= 1) {
			$(e).find("li:first").addClass("activeTeaser");
			return;
		}

		this.setup();
	};

	$.teaserRotator.fn = $.teaserRotator.prototype;
	$.teaserRotator.fn.extend = $.teaserRotator.extend = $.extend;

	$.teaserRotator.fn.extend({
		setup: function () {
			//Hide teasers and set the opacity of all images to 0, except for the first item
			this.container.find("li:gt(0)").hide().find("img").css({ opacity: .0 });

			//Hide all captions and set their opacity
			this.container.find(".teaserCaption").css({ opacity: .8, bottom: -(this.options.height) });

			//Get the first teaser and display it (set it to full opacity add activeTeaser class and set position of caption)
			this.container.find("li:first").addClass("activeTeaser").find(".teaserCaption").css({ bottom: 0 });

			//Set the timers for the teaser rotation, pause when hovering
			var self = this;
			this.timer = setInterval(function () { self.rotate(); }, this.options.speed);
			this.container.hover(
				function () { clearInterval(self.timer); },
				function () { self.timer = setInterval(function () { self.rotate(); }, self.options.speed); }
			);
		},
		rotate: function () {
			var current = this.container.find("li.activeTeaser");

			//Get next teaser and if last, get first instead
			var next = current.next("li");
			if (!next.length) next = this.container.find("li:first");

			//Fade in next teaser (activeTeaser class has higher z-index)
			next.addClass("activeTeaser").show().find("img").animate({ opacity: 1.0 }, 1000);

			//Slide down current caption, then slide up the next
			current.find(".teaserCaption").animate({ bottom: -(this.options.height) }, 500, function () {
				next.find(".teaserCaption").animate({ bottom: 0 }, 700);
			});

			//Fade out current teaser
			current.removeClass("activeTeaser").find("img").animate({ opacity: .0 }, 1000, function () { current.hide(); });
		}
	});

})(jQuery);

