/**
 * @author bheyer
 */
var boxSideMargins = 10;
var boxTopMargins = 5;
var activeBoxId = "";
var tapeWidth = 0;
var globalLeft = 0;

 /* SLIDER BOX CODE */
/* TODO: Combine with above code */
/* TODO: Generalize */
function scrollTo(boxId) {
	var destOffset = $("#" + boxId).offset().left;
	var currOffset = $("#" + activeBoxId).offset().left;
	var gotoLeftDist = (currOffset - destOffset) + globalLeft;
	globalLeft = gotoLeftDist;
		
	$(".sb_tape").animate({left: gotoLeftDist + boxSideMargins + "px"});
	
	activeBoxId = boxId;
}

function setTapeWidth() {	
	globalLeft = 0;
		
	activeBoxId = $(".sb_tape div:first").attr("id");
	
	tapeWidth = $(".sb_tape div").length * 
		(parseInt($(".sb_boxes").css("width").replace("px", "")) + boxSideMargins);
		
	$(".sb_tape").css({
		"top" : boxTopMargins,
		"left" : boxSideMargins,
		"width" : tapeWidth
	}).find("div").css({
		"width" : parseInt($(".sb_boxes").css("width").replace("px", "")) 
			- (2 * boxSideMargins) + "px",
		"height" : parseInt($(".sb_boxes").css("height").replace("px", "")) 
			- (2 * boxTopMargins) + "px",
		"marginRight" : boxSideMargins
	});	 
}
				
$(document).ready(function() {
	setTapeWidth();					
	
	$(".cv_sb_navi li").click(function() { $(this).find("a").click(); });
	$(".cv_sb_navi a").click(function(e) {
		if ($(this).attr("title") == "next") {
			if (activeBoxId == $(".sb_tape div:last").attr("id"))
				scrollTo($(".sb_tape div:first").attr("id"));
			else
				scrollTo($("#" + activeBoxId).next().attr("id"));			
		} else if (($(this).attr("title") == "prev")) {
			if (activeBoxId == $(".sb_tape div:first").attr("id"))
				scrollTo($(".sb_tape div:last").attr("id"));
			else
				scrollTo($("#" + activeBoxId).prev().attr("id"));			
		}			
		
		$(".cv_pie").css({"backgroundPosition" : "0 " + (($(".sb_tape div").index($("#" + activeBoxId)) + 1) * -300 )+ "px" });
		
		e.preventDefault();
		return false;
	});
	
	$(".cv_pie img").click(function(e) {
		scrollTo($(this).attr("id").replace("i_", ""));
		
		$(".cv_pie").css({"backgroundPosition" : "0 " + (($(".sb_tape div").index($("#" + activeBoxId)) + 1) * -300 )+ "px" });
	});
});