var $is_carousel_active;

var Kunc = {

	start: function() {
		$('html').addClass('js');
		this.makeAccordion();
		this.makeCarousel();
		this.makeGallery();
	},

	makeAccordion: function() {
		var $news = $('ul.news').find('li');
		$news.each(function(i) {
			var $item = $(this);
			if (!$item.is('.unfolded')) {
				$item.animate({ 'height': 30 }, 300).addClass('folded')
			} else {
				$item.removeClass('unfolded')
			}
			$item.hoverIntent({
				interval: 75,
				over: function() {
					$news.not(this).not('.folded').animate({ 'height': 30 }, 300, function() {
						$(this).addClass('folded');
					});
					$(this).animate({ 'height': 60 }, 300, function() {
						$(this).removeClass('folded')
					})
				},
				out: function() {}
			})
		});
	},

	makeCarousel: function() {
		var $carousel = $('div.carousel');

		if ($carousel.length) {
			var $gallery = $carousel.children('ul');

			function customControls(carousel) {

				var length = $gallery.find('li').length;
				var $controls_container = $('<div class="carousel-controls"></div>');
				for (var i = 0; i < length; i++) {
					var $control = $('<span>' + (i + 1).toString() + '</span>');
					if (i == 0) {
						$control.addClass('selected');
					}
					$controls_container.append($control);
				}

				$gallery.parent().prepend($controls_container)

				var $controls = $controls_container.find('span');
				var $buttons = $('.jcarousel-prev').add('.jcarousel-next');

				$controls.bind('click', function() {
					$controls.removeClass('selected');
					$(this).addClass('selected');
					var value = $(this).text();
					carousel.scroll($.jcarousel.intval(value));
					$buttons.attr('item', value);
				});


				$buttons.attr('item', '1').bind('click', function(e) {
					var type = this.className.split(' ')[0].split('-')[1];
					navigateCarousel(this, type)
					e.preventDefault();
				});

				function navigateCarousel(self, type) {
					var value = parseInt($(self).attr('item'));
					if (type == 'prev') {
						if (value > 1) { value--; }
					} else {
						if (value < length) { value++; }
					}
					carousel.scroll(jQuery.jcarousel.intval(value));
					$buttons.attr('item', value);
					$controls.removeClass('selected').eq(value - 1).addClass('selected');
				}

				$(window).bind('unload', function() {
					$buttons.removeAttr('item');
				});

			};

			$gallery.jcarousel({
				initCallback: customControls,
				buttonNextHTML: null,
				buttonPrevHTML: null
			})
		}
	},

	// returns an array containing the total amount of extra pixels added on top
	// of visibleWidth on the left and right sides. this happens due to the fact
	// that images don't fit precisely into visibleWidth.
	cloneElements: function(visibleWidth, galleryList, container) {
		var neededWidth = visibleWidth,
			elements, listItem,
			extraWidth = [],
			i = 0;

		elements = [];
		while(neededWidth > 0 && i < galleryList.length) {
			listItem = $(galleryList[i]);
			neededWidth -= listItem.width();
			listItem.clone().appendTo(container);
			i++;
		}
		extraWidth.push(-neededWidth);

		i = galleryList.length - 1;
		neededWidth = visibleWidth;
		while(neededWidth > 0 && i >= 0) {
			listItem = $(galleryList[i]);
			neededWidth -= listItem.width();
			listItem.clone().prependTo(container);
			i--;
		}
		extraWidth.push(-neededWidth);

		return extraWidth;
	},

	getTotalGalleryWidth: function(galleryList) {
		var width = 0,
			numItems = galleryList.find('li').each(function(i) {
				width += $(this).width();
			}).size();
		return width;
	},

	autoScrollGallery: function() {
		var $gallery = $('.gallery');

		if (!$gallery.length) {
			return;
		}

		var imagesWidth = 0,
			$galleryList = $gallery.find('ul'),
			$galleryControls = $([
				'<div class="gallery-prev"></div>',
				'<div class="gallery-next"></div>'
			].join("")),
			galleryWrapper = $("#carouselGalleryWrapper"),
			interval,
			wrapper = $galleryList.parent();

		galleryWrapper.append($galleryControls);

		var visibleWidth = $gallery.width(),
			originalWidth = this.getTotalGalleryWidth($galleryList);

		var extraWidth = this.cloneElements(visibleWidth, $galleryList.find("li"), $galleryList),
			totalWidth = this.getTotalGalleryWidth($galleryList)

		$galleryList
			.css("width", totalWidth)
			.css("margin-left", 0); // FIXME: no idea where this margin comes from, so get rid of it

		var carouselActive = true,
			animationConstant = 2,
			direction = 1,
			wrapperEl = wrapper[0],
			rightBound = totalWidth - visibleWidth,
			leftBound  = 864,
			rightJump = totalWidth - visibleWidth * 2 - extraWidth[0] - extraWidth[1],
			leftJump  = visibleWidth + extraWidth[0] + extraWidth[1],
			startScroll = visibleWidth + extraWidth[1],
			slowSpeed = 40,
			fastSpeed = 15;

		// reset to the correct starting position
		wrapperEl.scrollLeft = startScroll;

		function animateCarousel() {
			if (carouselActive) {
				wrapperEl.scrollLeft = wrapperEl.scrollLeft + animationConstant * direction;

				if (direction == 1 && wrapperEl.scrollLeft >= rightBound) {
					wrapperEl.scrollLeft = leftJump;
				} else if (direction == -1 && wrapperEl.scrollLeft <= 0) {
					wrapperEl.scrollLeft = rightJump;
				}
			}
		}

		var intervalId = setInterval(animateCarousel, slowSpeed);

		// handle stopping the carousel on mouse over and restarting again
		$gallery.hoverIntent({
			interval: 100,
			over: function() { carouselActive = false; },
			out:  function() { carouselActive  = true; }
		});

		var originalDirection;
		galleryWrapper.find(".gallery-next, .gallery-prev").hoverIntent({
			interval: 100,
			over: function() {
				originalDirection = direction;

				// temporary change in scrolling direction
				if (($(this).hasClass("gallery-next") && direction == -1) ||
					($(this).hasClass("gallery-prev") && direction ==  1)) {
						direction *= -1;
				}

				clearInterval(intervalId);
				intervalId = setInterval(animateCarousel, fastSpeed);
			},
			out: function() {
				direction = originalDirection;
				clearInterval(intervalId);
				intervalId = setInterval(animateCarousel, slowSpeed);
			}
		});
	},

	makeGallery: function() {
		$('.gallery-linked').not('.gallery-parent').find('a').lightBox()
	}

}

$(function() {
	Kunc.start();
	$(window).bind('load', function() {
	  Kunc.autoScrollGallery.call(Kunc);
	});
});