(function ($) {
	$.fn.carousel = function (target, config) {
		this.scrollInterval = 6000;
		$.extend(this, config || {});

		var slides, self = this,
			w = this.width(),
			h = this.height();

		this.stage = $('<div class="carousel-stage"/>');
		this.stage.css({
			width: w,
			height: h
		});
		this.wrap(this.stage);
		slides = this.find('.slider-div');
		this.lastSlide = slides.length - 1;
		this.css({
			width: w * slides.length,
			position: 'relative'
		});
		$('#prev').click(function () { self.prevSlide(); });
		$('#next').click(function () { self.nextSlide(); });
		// $('<img src="images/left.png">').insertBefore(this).css({
		// 			'position': 'absolute',
		// 			'margin-left': 35/-2 + 'px',
		// 			'margin-top': (h-35)/2 + 'px',
		// 			'z-index': 1000
		// 		}).click(function () { self.prevSlide(); });
		// 
		// 		$('<img src="images/right.png">').insertBefore(this).css({
		// 			'position': 'absolute',
		// 			'margin-left': w - (35/2) + 'px',
		// 			'margin-top': (h-35)/2 + 'px',
		// 			'z-index': 1000
		// 		}).click(function() { self.nextSlide(); });

		slides.addClass('slide').each(function (idx) {
			$(this).addClass('slide' + idx).css({
				'width': w,
				'height': h,
				'position': 'absolute',
				'top': 0,
				'left': w * idx
			});
		}).hover(
			function () { self.pauseScroll = true; },
			function () { self.pauseScroll = false; }
		);
		this.currentSlide = 0;
		this.nextSlide = function (wrap) {
			var end = self.currentSlide === self.lastSlide;
			if (!end || wrap) {
				self.updateSlide(end ? 0 : self.currentSlide + 1);
			}
			return self.currentSlide === self.lastSlide;
		};
		this.prevSlide = function (wrap) {
			var end = self.currentSlide === 0;
			if (!end || wrap) {
				self.updateSlide(end ? self.lastSlide : this.currentSlide - 1);
			}
			return self.currentSlide === 0;
		};
		this.updateSlide = function (pos) {
			self.currentSlide = pos;
			self.stop().animate({
				marginLeft: -(w * self.currentSlide)
			}, {
				duration: 1000,
				easing: 'swing'
			});
		};
		this.doAutoScroll = function () {
			if (!self.pauseScroll) {
				var dir = self.autoDirection === 'reverse',
					mode = self.autoScrollMode === 'bounce',
					end = self[dir ? 'prevSlide' : 'nextSlide'](!mode);
				if (mode && end) {
					self.autoDirection = dir ? 'forward' : 'reverse';
				}
			}
			setTimeout(self.doAutoScroll, self.scrollInterval);
		};
		this.updateSlide(this.currentSlide);
		setTimeout(this.doAutoScroll, this.scrollInterval);
	};

})(jQuery);

