var fadeTime = 6000;
var t = null;
var isHovering = false;
function fade_to(sender, id) {
	var speed = 600;
	
	var select_id = "#unit-feature #production_" + id;
	//if this is already the selected tab do nothing and break out
	if ($(select_id).hasClass("selected")) {
		return;
	}
	
	//select the right tab
	$("#more-productions li").removeClass("selected");
	$(sender).addClass("selected");
	
	//fade out the selected tab content
	$("#unit-feature .production.selected").fadeTo(speed, 0, function(){
		//test to see if this tab has been reselected
		if (!$(this).hasClass("selected")) {
			$(this).css({display: 'none'});
			$(this).addClass("hidden");
		}
	});
	
	$("#unit-feature .production.selected").removeClass("selected");
	$(select_id).addClass("selected");
	
	$(select_id).fadeTo(speed, 1, function(){}).removeClass("hidden");	
	
	clearTimeout(t);
	t = setTimeout(fadeCycle, fadeTime);
}

function fadeCycle() {
	//get the selected tab
	//get the next tab (or cycle round if it's the last one)
	//fadeTo() the next tab
	
	var next = $("#more-productions li.selected").next();
	if (next.length < 1) {
		next = $("#more-productions li:first");
	}

	var id = $(next[0]).attr("id");
	var parts = id.split("_");
	var index = parts[1];
	fade_to(next[0], index);

}

$(document).ready(function(){
	//set the default opacity values initially
	$("#unit-feature .production.hidden").css({opacity: '0'});
	$("#unit-feature .production.selected").css({opacity: '1'});
	
	if($("#unit-feature .production.selected").length) {
		$("#more-productions li a").click(function(){
			//return false;
		});
	
		$("#more-productions li").mouseover(function(){
			var id = $(this).attr("id");		
			var parts = id.split("_");
			var index = parts[1];
		
			fade_to(this, index);
		});
	
		$("#unit-feature").mouseover(function(){
			isHovering = true;
			clearTimeout(t);
		});
		$("#unit-feature").mouseout(function(){
			isHovering = false;
		
			clearTimeout(t);
			t = setTimeout(fadeCycle, fadeTime);
		});
	
		t = setTimeout(fadeCycle, fadeTime);
	}
});
