$(function() {

	/* homepage teasers */
	if (!$.teasers || $.teasers.length == 0) {
		return;
	} else {
		for (var i = 0, l = $.teasers.length; i < l; i++) {
			var c = $.teasers[i];
			if (c.src == "" || c.url == "" || c.alt == "" || c.title == "") {
				$.teasers.splice(i, 1);
				break;
			}
		}
	}

	var Carousel = {

		registry: {
			choices: [],
			teasers: []
		},

		container: $("div.teasers"),
		choices: $("<ul id='choice'></ul>"),

		loop: null,
		next: 1,

		start: function() {
			Carousel.loop = setInterval(function() {
				Carousel.container.find("div").fadeOut(2000, function() {
					$(this).remove();
				});
				Carousel.container.append(Carousel.registry.teasers[Carousel.next].fadeIn(2000));

				Carousel.choices.find("span.active").removeClass("active");
				$("#teasertext" + Carousel.next).addClass("active");

				Carousel.next = (Carousel.next == ($.teasers.length - 1)) ? 0 : Carousel.next + 1 ;

			}, 7000);
		},

		startAt: function(n) {
			Carousel.stop();
			if ((Carousel.next - 1) != n) {
				if ((Carousel.next - 1) != n && Carousel.next != 0) {
					Carousel.container.find("div").fadeOut(500, function() {
						$(this).remove();
					});
				}
				Carousel.container.append(Carousel.registry.teasers[n].fadeIn(500));
				Carousel.next = (n == ($.teasers.length - 1)) ? 0 : n + 1 ;
			}
			Carousel.choices.find("span.active").removeClass("active");
			$("#teasertext" + n).addClass("active");
			Carousel.start();
		},

		stop: function() {
			clearInterval(Carousel.loop);
		},

		init: function() {

			$.each($.teasers, function(i, obj) {
				Carousel.registry.choices.push($("<li><span id='teasertext" + i + "' class='teasertext'><button id='button" + i + "' title='" + obj.alt + "'>" + (i + 1) + "</button><label for='button" + i + "'>" + obj.title + "</label></span></li>"));
				Carousel.registry.teasers.push($("<div id='teaser" + i + "' style='display:none;position:absolute;'><a href='" + obj.url + "' title='" + obj.title + "'><img src='" + obj.src + "' alt='" + obj.alt + "'/></a></div>"));
			})

			$.each($(Carousel.registry.choices), function(i, obj) {
				$(obj).find("button")
						  .data("n", i)
						  .click(function(e) {
						  	  Carousel.startAt($(this).data("n"));
							  e.preventDefault();
						  })
						  .end()
					  .appendTo(Carousel.choices);
			});

			Carousel.choices.find("span:first").addClass("active");

			this.container.empty()
						  .prepend(Carousel.choices)
						  .append(Carousel.registry.teasers[0].show());

			this.start();

		}

	}

	Carousel.init();


});