﻿// slideshow
(function ($) {
	$.fn.slideshow = function (options) {
		var opts = $.extend({}, $.fn.slideshow.defaults, options);
		return $(this).each(function () {

			var o = $.meta ? $.extend({}, opts, $this.data()) : opts,
			slideshow = $(this),
				slides = slideshow.find("li"),
				slides_length = slides.length,
				transition = 500;

			slideshow
				.bind('play', function () { play(); })
				.bind('next-slide', function (e, play) { next(play); })
				.bind('pause', function () { pause(); })
				.data("currentSlide", 0)
				.find("li:gt(0) span")
					.hide()
					.end()
				.find("li:gt(0)>img")
					.css({ "opacity": 0.5 })
					.end()
				.find("li>img")
					.click(function (e) {
						e.preventDefault();
						var next = $(this).parent().index(),
							visible = slideshow.data("currentSlide");
						if (next === visible) {
							return;
						}
						slideIn(e, visible, next);
						slideshow.trigger('pause');
					})
					.end()
				.find("nav a.pause")
					.click(function (e) {
						e.preventDefault();
						slideshow.trigger('pause');
					})
					.end()
				.find("nav a.play")
					.click(function (e) {
						e.preventDefault();
						slideshow.trigger('pause');
						next();
						//slideshow.trigger("play");
					})
					.end()
				.trigger("play");

			function play() {
				slideshow.data('timer', setTimeout(function () { next(); }, opts.slide_transition));
			}

			function pause() {
				clearTimeout(slideshow.data('timer'));
			}

			function slideIn(e, from, to) {
				slideshow.find("li span:visible").fadeOut(transition, "easeInOutExpo");
				slideshow.find("li:eq(" + from + ") >img").css({ "opacity": 0.5 });
				slideshow.find("li:eq(" + to + ") span").fadeIn(transition, "easeInOutExpo");
				slideshow.find("li:eq(" + to + ") >img").css({ "opacity": 1 });
				slideshow.data("currentSlide", to)
				return slideshow.data("currentSlide");
			}

			function next(play) {
				slideIn(false, current_slide(), next_slide());
				slideshow.trigger('pause');
				play !== false && slideshow.trigger('play');
			}

			function next_slide() {
				var next = slideshow.data('currentSlide') + 1;
				if (next === slides_length) { next = 0; }
				return next;
			}

			function current_slide() {
				return slideshow.data("currentSlide");
			}
		});

	}

	$.fn.slideshow.defaults = {
		slide_transition: 3000
	};
})(jQuery);
