function handleTopStoriesFlip(displaySelectorElem) {
	var displaySelector = $(displaySelectorElem);
	var displaySelectorImagesArray = displaySelector.children('img');
	displaySelector.data('selectedIndex', 0);
	displaySelectorImagesArray.each(function(index) {
		if($(this).attr('class') == 'selected') {
			$(this).parent().data('selectedIndex', index);
		}
	});
	var newIndex = displaySelector.data('selectedIndex') + 1;
	if(newIndex > (displaySelectorImagesArray.length-1)) {
		newIndex = 0;
	}
	handleTopStoriesAlteration(displaySelectorImagesArray[newIndex]);
}

function handleTopStoriesAlteration(displaySelectorImgElem, stopAnim) {
	var topStoriesSelectorImgPath = '/images/widgets/topStories/selector/';
	var topStoriesSelectorSelectedImgPath = 'selected.png';
	var topStoriesSelectorOtherImgPath = 'other.png';
	var displaySelectorImg = $(displaySelectorImgElem);
	if(typeof displaySelectorImg == 'undefined' || typeof displaySelectorImg.attr('id') == 'undefined')
	{
		return false;
	}
	if(typeof stopAnim == 'undefined') {
		stopAnim = false;
	}
	if(stopAnim) {
		window.clearInterval(displaySelectorImg.parent().data('flipIntervalId'));
	}
	if(!displaySelectorImg.hasClass('selected')) {
		displaySelectorImg.parent().children('.selected').each(function () {
			var thisElem = $(this);
			var thisSrc = thisElem.attr('src');
			var regExp = new RegExp(topStoriesSelectorSelectedImgPath + '$');
			var newSrc = thisSrc.replace(regExp, topStoriesSelectorOtherImgPath);
			thisElem.removeClass('selected');
			thisElem.attr('src', newSrc);
		});
		displaySelectorImg.addClass('selected').each(function () {
			var thisElem = $(this);
			var thisSrc = thisElem.attr('src');
			var regExp = new RegExp(topStoriesSelectorOtherImgPath + '$');
			var newSrc = thisSrc.replace(regExp, topStoriesSelectorSelectedImgPath);
			thisElem.attr('src', newSrc);
		});
		var articleId = displaySelectorImg.attr('id').split('_')[1];
		var contentElemId = 'topStoryEntry_' + articleId;
		var cElems = displaySelectorImg.parents('.topStories').find('.content #' + contentElemId);
		if(cElems.length > 0) {
			cElems.parent().children(':visible').each(function() {
				$(this).stop().hide();
			});
			cElems.stop().show();
		}
	}
}

$(document).ready(function() {
	if(typeof widget_hasTopStories != "undefined" && widget_hasTopStories) {
		$('.displaySelector img').click(function() {
			handleTopStoriesAlteration(this, true);
		});
		$('.displaySelector').each(function() {
			if($(this).children('img').length > 0) {
				var thisElem = this;
				var flipIntervalId = window.setInterval(function() { handleTopStoriesFlip(thisElem); }, 5000);
				$(this).data('flipIntervalId', flipIntervalId);
			}
		});
	}
});
