$(function(){
	var autoscrollDelay = 6000;

	var hotAnimationHandler, autoscrollHandler = null;
	var cacheImgs = new Array();
	var currentItemIndex = 0;
	var enabled = true;
	
	var items = $("#hot-carousel").find("li");
	
	var hot = {
		container: $("#hot-text-container"),
		img: $("#hot-img"),
		imgTopContainer: $("#hot-img-top"),
		imgBottom: $("#hot-img-btm"),
		title: $("#hot-title"),
		text: $("#hot-text"),
		imgLink: $("#hot-img-link"),
		link: $("#hot-link")
	}
	
	function displayHotItem(itemIndex, noFading) {
		resetAutoscroll();

		if (itemIndex != currentItemIndex) {
			currentItemIndex = itemIndex;
			var item = items.eq(currentItemIndex);

//			hot.img[0].src = item.attr("big_image");
			hot.imgBottom[0].src = item.attr("big_image");
			
			if (noFading) {
				hot.img[0].src = item.attr("big_image");
			} else {
				hot.imgTopContainer.stop().fadeOut(800, function(){
					hot.img[0].src = item.attr("big_image");
					hot.imgTopContainer.css("opacity", "").show();
				});
			}
			
			hot.container.stop().css("top", "92px");
			hot.title.removeClass("debates videos blogs custom-page").addClass(item.attr("csstype"));
			hot.link.text(item.attr("title")).attr("href", item.attr("link_url"));
			hot.text.html(item.attr("fulltext"));
			hot.imgLink[0].href = item.attr("link_url");

			window.clearTimeout(hotAnimationHandler);
			hotAnimationHandler = window.setTimeout(function(){
				hot.container.stop().animate({
					top: 0
				}, 350, "linear", function(){
					hot.container.css("top", 0);
				});
			}, 700);
		}
	}

	items.mouseenter(function(){
		var itemIndex = items.index($(this));
		displayHotItem(itemIndex, true);
	}).each(function(){
		var img = new Image();
		img.src = this.getAttribute("big_image");
		cacheImgs.push(img);
	});

	
	resetAutoscroll();

	$("#hot-container").hover(function(){
		enabled = false;
	}, function(){
		enabled = true;
		resetAutoscroll();
	});

	function resetAutoscroll(){
		window.clearTimeout(autoscrollHandler);
		autoscrollHandler = window.setTimeout(scrollToNextItem, autoscrollDelay);
	}
	
	function scrollToNextItem(){
		if (enabled) {
			var nextIndex = currentItemIndex + 1;
			if (nextIndex >= items.length) {
				nextIndex = 0;
				window.sportpostApplication.carousel.controller.scroll(1);
			} else {
				window.sportpostApplication.carousel.controller.next();
			};
			displayHotItem(nextIndex);
			
			resetAutoscroll();
		}
	}
	
	
//	activate top news hover	
	$(document).bind("activateContext", function(event, context){
		if (context.id == "news-block") {
			var block = $(context);
			var icon = block.find(".top-news-ico");
			block.find(".news-item").mouseover(function(){
				icon.css("top", $(this).position().top + 16)
			});
		}
	})
});
