var delay = 5000;
var current_index = -1;
var rotation_paused = false;
var static_flag = false;

function init_rotation() {
	
	rotation_items = $('#rotating-banners div.r-banner').length;
	current_index = 0;
	
	for (var i = 0; i < rotation_items; i++) {
		
		$('#r-tab'+i).get(0).tab_idx = i;
		$('#r-tab'+i).mouseup(function(){
			static_flag = true;
			rotate($(this).get(0).tab_idx,false);
		});
		
	}
	
	
	$('#rotating-banners').mouseover(function() {
		if (!static_flag) {
			rotation_paused = true;
		}
	} );
	
	$('#rotating-banners').mouseout(function() { 
		if (!static_flag) {
			rotation_paused = false;
		}
	} );
	
	setTimeout("run_auto_rotation()", delay);
	
}

function run_auto_rotation() {
	
	if (!rotation_paused && !static_flag) {
		
		var new_index = (current_index + 1) % rotation_items;
		rotate(new_index,true);
	}
	
	setTimeout("run_auto_rotation()", delay);
	
}

function rotate (new_index,fade) {
	
	if (current_index != -1) {
		$('#r-tab' + current_index).removeClass("selected");
		if (fade) {
			$('#banner-' + current_index).css("opacity",1).removeClass("selected").animate({ opacity: 0.1 }, 800);
		} else {
			$('#banner-' + current_index).removeClass("selected")
		}
	}
	
	$('#r-tab' + new_index).addClass("selected");
	if (fade) {
		$('#banner-' + new_index).css("opacity",0.1).addClass("selected").animate({ opacity: 1 }, 800);
	} else {
		$('#banner-' + new_index).css("opacity",1).addClass("selected");
	}
	
	current_index = new_index;
}

$(document).ready(function() {
	init_rotation();
});