(function($, window, undefined) {
	var featureDuration = 5000,
		fadeDuration = 500,
		allPanels = $('#homepage-feature-images div'),
		allImages = $('#homepage-feature-images img'),
		availableImages = $('#homepage-feature-images .loaded'),
		timerStarted = false,
		activeImage,
		activeIndex,
		activeItem,
		nextAvailableImage,
		img,
		rotateTimer,
		rotateImage = function() {
			activeImage = availableImages.filter('.active');
			activeIndex = availableImages.index(activeImage[0]);
			nextAvailableImage = $(availableImages[activeIndex == availableImages.length - 1 ? 0 : activeIndex + 1]);
			activeImage.fadeOut(fadeDuration, function() {
				activeImage.removeClass('active');
			});
			nextAvailableImage.fadeIn(fadeDuration, function() {
				nextAvailableImage.addClass('active');
			});
			rotateTimer = setTimeout(rotateImage, featureDuration);
		};
	allImages.load(function(e) {
		img = $(this);
		if(img.attr('src').match(/\/images\/features\/blank\.gif\?/)) {
			return;
		}
		activeItem = img.closest('div').addClass('loaded');
		if(availableImages === undefined || availableImages.length < allPanels.length) {
			availableImages = $('#homepage-feature-images .loaded');
		}
		if(!timerStarted) {
			if(!activeItem.hasClass('active')) {
				availableImages.removeClass('active');
				activeItem.addClass('active');
			}
			timerStarted = true;
			if(rotateTimer) {
				clearTimeout(rotateTimer);
			}
			rotateTimer = setTimeout(rotateImage, featureDuration);
		}
	});
	$(window).load(function() {
		$('#homepage-feature-images div:not(.loaded)').each(function(i, item) {
			item = $(item);
			if(!item.find('img').attr('src').match(/\/images\/features\/blank\.gif\?/)) {
				item.addClass('loaded');
			}
		});
		timerStarted = true;
		if(rotateTimer) {
			clearTimeout(rotateTimer);
		}
		rotateTimer =setTimeout(rotateImage, featureDuration);
	});
	$(function() {
		$('#homepage-feature-images img').each(function(i, img) {
			img = $(img);
			setTimeout(function() {
				img.attr('src', img.attr('src').replace(/\/images\/features\/blank\.gif\?/, ''));
			}, 10);
		});
	});
})(jQuery, this);
