﻿jQuery(document).ready(function($) {
	var slides = $('.slideShow-slide');
	var prevButton = $('.slideShow-prev a');
	var nextButton = $('.slideShow-next a');
	var playButton = $('.slideShow-play a');

	var id = $('.slideShow-overlay')[0].id;

	var currentSlide;
	var currentSlideIndex = function() {
		return slides.index(currentSlide);
	};
	var nextSlideIndex = function() {
		var index = currentSlideIndex();
		if (index != totalSlides() - 1) return index + 1;
		return 0;
	};

	var prevSlideIndex = function() {
		var index = currentSlideIndex();
		if (index == 0) return totalSlides() - 1;
		else return index - 1;
	};
	var totalSlides = function() {
		return slides.length;
	};

	var showSlide = function(index) {
		var slideToShow = slides.eq(index);

		if (currentSlide) currentSlide.fadeOut('normal', function() {
			slideToShow.fadeIn();
			slides.not(slideToShow).hide();
		});
		else {

			slideToShow.show();
			slides.not(slideToShow).hide();

		}
		currentSlide = slideToShow;
	};

	var showNextSlide = function() {
		showSlide(nextSlideIndex());
	};

	var showPrevSlide = function() {
		showSlide(prevSlideIndex());
	};

	nextButton.click(function() {
		stopShow();
		showNextSlide();
		return false;
	});

	prevButton.click(function() {
		stopShow();
		showPrevSlide();
		return false;
	});

	var playing = false;

	var timeout;

	var startShow = function() {
		playing = true;
		timeout = setTimeout(function() {
			showNextSlide();
			startShow();
		}, 5000);
		playButton.addClass('playing');
		playButton.removeClass('paused');
		playButton.text('Pause');
	};
	var stopShow = function() {
		clearTimeout(timeout);
		playButton.addClass('paused');
		playButton.removeClass('playing');
		playButton.text('Play');
		playing = false;
	};

	playButton.click(function() {
		if (playing) {
			stopShow();
		}
		else {
			startShow();

		}
		return false;
	});

	$.each(OakTree.Web.UI.WebControls.Overlay, function(i, overlay) {
		if (overlay.controlID == id) {
			overlay.api.onClose(function() {
				stopShow();
			});
		}
	});


	showSlide(0);
	startShow();
});