$(document).ready(function() {
	// Find and count the slider images.
	var img_count = $('#slider li').size(), top_z = 6, bottom_z = 5;

	if (img_count > 1) {
		// Reset all items.
		$('#slider li img').css('z-index', bottom_z).hide();
		$('#slider li span').removeClass('active');

		// Set first item.
		$('#slider li img').first().css('z-index', top_z).show();
		$('#slider li span').first().addClass('active');

		function switchImages() {
			// Find current and next element.
			var $current = $('#slider li span.active').parent(), $next = ($('#slider li span.active').parent().next().size() !== 0) ? $('#slider li span.active').parent().next() :  $('#slider li').first();

			$current.children('span').removeClass('active');
			$next.children('span').addClass('active');

			$current.children('img').fadeOut(1500).css('z-index', bottom_z);
			$next.children('img').fadeIn(1500).css('z-index', top_z);

			setTimeout(switchImages, 4000);
		}

		setTimeout(switchImages, 4000);
	}
});
