var newsitems;
var curritem=0;
var index=1;
var id; 
var stopClicked=false;
var rotationSpeed;

$(document).ready(function() {
 
  newsitems = $("#spotlight_img img").hide().size();
  $("#spotlight_txt table").hide();
  
  $('#picCount').html(index + " of " + newsitems);
  rotationSpeed = $('#rotateSpeed').attr("title");
  // displays the first item
  $("#spotlight_img img:eq(0)").fadeIn('slow');
  $("#spotlight_txt table:eq(0)").show();
  
  play(true, false);
	
	$("#next2").click(function(){
		stop(true, false);
		rotate();
		return false;
	});
	
	$("#prev2").click(function(){
		stop(true, false);
		previous();
		return false;
	});
	
	$("#pause").click(function(){
		stop(true, false);
		return false;
	});
	$('#play').click(function() {
		play(true, false);
		return false;
	});
	$("#spotlight_img").hover(function() { stop(false, true); return false; }, function() { play(false, true); return false; });
});

function skipForward() {
	document.getElementById("skip_rs").focus();
}
	
function skipBackward() {
	document.getElementById("begin_rs").focus();
}

function rotate() {
	// hide current
    $("#spotlight_img img:eq("+curritem+")").hide();
	$("#spotlight_txt table:eq("+curritem+")").hide();
  
    // increment to next item
    curritem = ++curritem % newsitems;
	index=curritem + 1;
    
    // fade in current item
	$("#spotlight_txt table:eq("+curritem+")").show();
	$("#spotlight_img img:eq("+curritem+")").fadeIn('slow');
	$('#picCount').html(index + " of " + newsitems);
}

function previous() {
		
	// hide current
    $("#spotlight_img img:eq("+curritem+")").hide();
	$("#spotlight_txt table:eq("+curritem+")").hide();
    
    // increment to next item
    curritem = (curritem - 1)
	if(curritem == -1){
		curritem = newsitems - 1;
	}
	
	index=curritem + 1;
 
    // fade in current item
	$("#spotlight_txt table:eq("+curritem+")").show();
	$("#spotlight_img img:eq("+curritem+")").fadeIn('slow');
	$('#picCount').html(index + " of " + newsitems);
}

function stop(changeButton, mouseHover){
	clearInterval(id);
	if(changeButton && !mouseHover){
		$("#pause").removeClass();
		$("#pause").addClass('rsHideElement');
		$("#play").removeClass();
		$("#play").addClass('rsShowElement');
		stopClicked=true;
	}
}

function play(changeButton, mouseHover){
	if(mouseHover){
		if(!stopClicked){
			// reset interval upon page launch and stop
			clearInterval(id);
			id=setInterval(rotate, rotationSpeed);
		}
	} else if(!mouseHover){
		if(stopClicked){
			rotate();
			id=setInterval(rotate, rotationSpeed);
			$("#pause").removeClass();
			$("#pause").addClass('rsShowElement');
			$("#play").removeClass();
			$("#play").addClass('rsHideElement');
			stopClicked=false;
		}
		else if(!stopClicked){
			id=setInterval(rotate, rotationSpeed);
		}
	}
}