/*** Promitacka ***/
$.fn.slideshow = function(o) {
	var defaults = {
		slideSpeed: 500,
		slideFx: "linear",
		autorun: true,
		autorunSpeed: 4000
	};
	o = $.extend(defaults, o);

	return this.each(function() {
		var me = $(this),
			activeItem,
			items = $(".navigation .dots a", this).size(),
			$button = $(".navigation .dots a", this),
			buttonWidth =  $button.width() + parseInt($button.css('paddingLeft')) + parseInt($button.css('paddingRight')),
			itemWidth = me.find(".items .in div").width(),
			itemsContainerWidth = itemWidth*items,
			timer,
			mouseOver;

		if (location.hash && parseInt((location.hash.slice(1)).replace("item-","")) <= items) {
			activeItem = parseInt((location.hash.slice(1)).replace("item-",""));
		} else {
			activeItem = 1;
		};

		/* dynamicke manipulace s html */
		if (items > 0) {
			$(".items .in", me).css({ width: itemsContainerWidth });

			/* fix position and align */
			buttonsWidth = (buttonWidth * items) + 1;
			var marLeft = parseInt( (itemWidth/2)-(buttonsWidth/2) );
			$(".dots", me).css({ width: buttonsWidth, margin: "0 0 0 "+marLeft+"px" });

			show(me, activeItem);
		}

		/* ovladani navigace */
		$(".navigation .dots a", me).click(function() {
			activeItem = parseInt($(this).text());
			show(me, activeItem);
			return false;
		});
		$(".navigation a.next", me).click(function() {
			activeItem = activeItem + 1;
			if (activeItem > items) { activeItem = 1; }
			show(me, activeItem);
			return false;
		});
		$(".navigation a.previous", me).click(function() {
			activeItem = activeItem - 1;
			if (activeItem == 0) { activeItem = items; }
			show(me, activeItem);
			return false;
		});

		/* funkce autorun */
		if ((o.autorun) && (items > 0)) {
			me.ready(function() {
				timer = setTimeout(autoSlide,o.autorunSpeed);
			});
		};
		me.mouseover(function() {
			mouseOver = true;
		});
		me.mouseout(function() {
			mouseOver = false;
		});

		function show(me, item) {
			/* 22 - sirka odkazu (TODO nacist dynamicky) */
			var bgPosition = ((item-1)*22) + (item);
			$(".navigation .dots a", me).removeClass("active");
			$("span.active", me).stop().animate({backgroundPosition:"(" + bgPosition + "px 0px)"});
			$(".navigation .dots a", me).eq(item-1).addClass("active");

			var offset = - (itemWidth *(item - 1));
			$('.items .in', me).animate({ marginLeft: offset }, o.slideSpeed, o.slideFx);
		};

		function autoSlide() {
			if (!mouseOver) {
				if (activeItem == items) {
					activeItem = 1;
				} else {
					activeItem = activeItem + 1;
				}
 			show(me, activeItem)
 			}
			timer = setTimeout(autoSlide, o.autorunSpeed);
		};

	});
};

