$(document).ready(function() {
	var flashes = new Flashes($('#flashes-list .wrapper'));

	if(flashes.length > 1) {
		flashes.start();

		$('#flashes-list').hover(
			function() { flashes.stop(); },
			function() { flashes.start(); }
		);

		$('#flashes-list').mousewheel(
			function(event, delta) {
				flashes.delta(delta);
				event.preventDefault();
			}
		);
	}
});

function Flashes($container) {
	this.$images = $container.children('img');
	this.$contents = $container.children('div.content');

	this.step = 0;
	this.duration = 300;
	this.easing = 'easeOutQuint';

	this.height = $container.height();
	this.length = this.$images.length;
	this.timer = null;
	this.animating = false;
}

Flashes.prototype.start = function() {
	var self = this;
	this.step = (this.length + this.step) % this.length;

	this.$images.each(function(index) {
		if(index == self.step) $(this).css({display: 'block', opacity: 1});
		else $(this).css({display: 'none', opacity: 0});
	});

	this.$contents.each(function(index) {
		if(index == self.step) $(this).css({top: 0, opacity: 1});
		else $(this).css({top: self.height, opacity: 0});
	});

	this.timer = setInterval(function() {
		self.next();
	}, 19500);
}

Flashes.prototype.stop = function() {
	clearInterval(this.timer);
}

Flashes.prototype.next = function() {
	this.delta(1);
}

Flashes.prototype.previous = function() {
	this.delta(-1);
}

Flashes.prototype.delta = function(delta) {
	this.move(this.step + delta, delta < 0);
}

Flashes.prototype.move = function(step, invert) {
	step = step % this.length;
	var self = this;

	if(! this.animating) {
		this.animating = true;

		setTimeout(function() {
			self.animating = false;
		}, this.duration + 50);

		this.hide(this.step, invert);
		this.show(step, invert);

		this.step = step;
	}
}

Flashes.prototype.show = function(step, invert) {
	$(this.$images.get(step))
		.css({display: 'block', opacity: 0})
		.animate({opacity: 1}, this.duration, this.easing);

	$(this.$contents.get(step))
		.css({top: invert ? -this.height : this.height, opacity: 0})
		.animate({top: 0, opacity: 1}, this.duration, this.easing);
}

Flashes.prototype.hide = function(step, invert) {
	$(this.$images.get(step))
		.css({display: 'block', opacity: 1})
		.animate({opacity: 0}, this.duration, this.easing, function() {
			$(this).css({display: 'none'});
		});

	$(this.$contents.get(step))
		.css({top: 0, opacity: 1})
		.animate({top: invert ? this.height : -this.height, opacity: 0}, this.duration, this.easing);
}



