var sm_test = 0;

//Config Vars
	var maxWidth = 500;    //width of the front card in px.
	var incrWidth = 40;    //increment value for width (in pixels). Left offset is also calculated from this; best as an EVEN number.
	var maxMarginTop = 150;//Distance from the top of the container of the BOTTOM (front-most) card in px
	var incrMarginTop = 22;//max increment decrease value for top margin (in pixels)s
	var startRgbVal = 90;  //decrease this number to make the cards closer to the front darker (and the steps back in color bigger).
	var cardsVisible = 11; // total number of visible cards at any time. (The back most will be almost white)
	var animTimeRef = 500;   //miliseconds for one iteration of card movement
	var animTime;		//adjusted anim time
	var colorFadeAnimTime = 200; //miliseconds for card color fade back in.  Note: if card colors are "sticking" (not fading out) reduce this number
	var headerMaxFontSize = 18; //size in pixels
//End config vars

var rgbIncr = Math.round((255-startRgbVal)/(cardsVisible - 2)); //This calculates how much further toward white each further back card should be
var stepDown = incrWidth/maxWidth; //determines the % step down in each card size, for use in determining font
//var stepDown = incrMarginTop/maxMarginTop; //determines the % step down in each card size, for use in determining font
var headerFontSizeIncr = headerMaxFontSize *stepDown;
var colorPlaceHolders = []; //holds the grey shades to switch back to on card mouse out (offCard)
var swfCardContents = []; //holds swfObjects
var cardVals = []; //holds the calculated dimensions/settings for each position in the visible stack
var iterationCounter = 0;
var curDecadeID;
var frontCardIndex;
var finalCardIndex;
var mouseWheelActive =true;
var movesThreshold = cardsVisible-3; //threshold of moves above which cards jump closer rather than animate

if(navigator.userAgent.indexOf('MSIE')>0){
	movesThreshold = 1; //ie can handle fewer moves
}


var clickedCard;

var decColors = [];
var inactiveColor = "#acacac";
var bgColor = "#FFFFFF";

$(document).ready(function(){
	////////////////////
	///////////////test
	////////////////////
	$("#forwardBut").click(function(){
		frontCardIndex = $('div.card','#card_container').index($(".front_card"));
		iterationCounter =1;
		if(frontCardIndex != 0){
			moveStackForward(); //don't move forward if the front card is the final card
		}
	});
	$("#backBut").click(function(){
		frontCardIndex = $('div.card','#card_container').index($(".front_card"));
		iterationCounter =1;
		if(frontCardIndex != finalCardIndex){  //don't move back if the front card is the first card
			moveStackBackward();
		}
	});		
	////////////////////
	////////////////////
	initColors();
	initCards();
//	alert("x");
	initTimelineUl();
//	alert("y");
 	bindMousewheel();
//	alert("z");
	bindCardClicks();
//	alert("a");
//print_r(cardVals);
	return false;
});	//doc.ready
/**
	initCards 
	sets up all the cards for their initial state
	The last card in the list is sent to the front, and given an id of "front_card", cards tops are rounded incrementally, spaced from top of container incr., width and gray shade set incrementally.
	@param		int		jump 		index of target front card, to be used instead of actualy front card.
	@param		string	direction 	"forward" or "back"
	@return 			Null
*/
function initCards(jump, direction){
	if(jump){
		//remove classes and hide all cards
		$('div.card','#card_container').hide();
		//set finalCardIndex to jump val
		finalCardIndex=jump;
	}else{
		finalCardIndex = $('div.card','#card_container').length -1;
	}
	$('div.card','#card_container').each(function(){					//loop through all of the cards, set them to the correct initial state
		var thisIndex = $('div.card','#card_container').index(this);
		$(this).removeClass("inFrontOfVisible").removeClass("behindVisible").removeClass("front_card"); //remove existing classes, just in case we're jumping
//		alert("$('div.card','#card_container').each: this index: " + thisIndex + "  contents: " + $(this).html());
		var indexDifference = finalCardIndex - thisIndex; 		//how many places $this is away from final card
		if(indexDifference < cardsVisible && indexDifference>=0){		//card is in visible range
//			console.log("indexDifference: " + indexDifference);
			setDimensions(indexDifference, $(this));
		}else if(indexDifference>0){ //outside of visible range, in back
			$(this).css("display", "none").addClass("behindVisible");
		}else{ //outside of visible range, in front
			$(this).css("display", "none").addClass("inFrontOfVisible");
		}
		
		if($(this).find('.swfWrapper').length>0){
			storeSwfObjects($(this));
		}
	}); //each (allCards)	
	if(!jump){ //this is only for the first init
 		$('#coverUpDiv').fadeOut(1);
//mouseOver card effect	
		$('div.card','#card_container').hover(function(){
				overCard($(this))
			},
			function(){
				thisIndex = $('div.card','#card_container').index(this); //find the index to know which color to switch back to (from the colorPlaceHolders array)
				offCard($(this), thisIndex);
		});
		setTimeout("activateFrontSwf()",animTimeRef);
		if(navigator.userAgent.indexOf('MSIE 6')>0){
			DD_belatedPNG.fix('.card, h2');
		}	
	}else{//jumped, now anim
		frontCardIndex = jump;
		if(direction=="back"){
//			console.log("finalCardIndex: " + finalCardIndex + "  iterationCounter:" + iterationCounter);
			moveStackBackward();
		}else{
			moveStackForward();
		}
	}
	return false;
}

function initColors(){
	decColors[4] = $("li#decade_4").css("color");
	decColors[5] = $("li#decade_5").css("color");
	decColors[6] = $("li#decade_6").css("color");
	decColors[7] = $("li#decade_7").css("color");
	decColors[8] = $("li#decade_8").css("color");
	decColors[9] = $("li#decade_9").css("color");
	decColors[0] = $("li#decade_0").css("color");
	decColors[1] = $("li#decade_1").css("color");
	return false;
}

/**
	Calculates how far clicked card is from front, passes value to moveStackForward
*/
function calcForwardMotion(){
	frontCardIndex = $('div.card','#card_container').index($(".front_card"));
//alert("calcForwardMotion frontCardIndex: " + frontCardIndex);
	if(frontCardIndex == 0){ //don't move forward if the front card is the final card
		return false;
	}
	thisCard = clickedCard;
	var thisIndex = $('div.card','#card_container').index(thisCard);
	iterationCounter = frontCardIndex - thisIndex;
	if(iterationCounter>movesThreshold){
		jumpCards(thisIndex, iterationCounter);
		return true
	}
	moveStackForward();
}

/**
	moveStackForward
	checks each card for position, runs appropriate animation on it
	@param integer frontIndex	The index of the card at the front of the stack at the outset of the function execution
	@return 			Null
*/
function moveStackForward(){
//	animTime = animTimeRef / (iterationCounter*iterationCounter) + iterationCounter*iterationCounter;
	animTime = animTimeRef / (iterationCounter*iterationCounter);
	dropFrontCard($('div.card','#card_container').eq(frontCardIndex)); 
	$('div.card','#card_container').each(function(){
		var thisIndex = $('div.card','#card_container').index(this);
		indexDiff1 = frontCardIndex-thisIndex; //indexDiff1 to not collilde with indexDiff. used to calculate grayshade, size, etc.
		//console.log("thisIndex: " + thisIndex + "  frontCardIndex: " + frontCardIndex + "  indexDiff1: " + indexDiff1);
		if(thisIndex < frontCardIndex && thisIndex > frontCardIndex - cardsVisible){	//card is visible & not front card  //run moveCardForward
//	alert("thisIndex: " + thisIndex + "  indexDiff1: " + indexDiff1 + "  frontCardIndex: " + frontCardIndex);
			if(thisIndex == (frontCardIndex-1)){
				$(this).addClass("front_card");
				if($(this).find("object").length>0){
					relVal = $(this).attr('rel');
					replaceSwfObject(thisCard, relVal)
				}
			}
			moveCard(indexDiff1, $(this), "forward");
		}else if(thisIndex == (frontCardIndex-cardsVisible)){//Not visible. check if it's just behind the last card: run fadeInBackCard 
			fadeInBackCard(indexDiff1, $(this));
		}
	//the current index is greater (card is inFrontOfStack), ignore it, do nothing
	});
	iterationCounter--;
	if(iterationCounter>0){
		frontCardIndex--;
//alert("iterationCounter>0 frontCardIndex: " + frontCardIndex);
		moveStackForward();
		return false;
	}else{
	bindCardClicks();	
	openCurEventLi(); //change to openCurYearLi
	activateFrontSwf();
	return false;
}
}


/**
	@param String direction "forward" or "back"
*/

function moveCard(indexDiffIn, thisCard, direction){
	if(direction=="forward"){
		indexDiff = indexDiffIn-1; //decrement because we want the card to be 1 closer to the front	
//	alert("moveCard forward indexDiff: " + indexDiff);
	}else if(direction=="back"){
		indexDiff = indexDiffIn+1; //increment because we want the card to be 1 closer to the back		
//	alert("moveCard back indexDiff: " + indexDiff);
	}
	if(thisCard.hasClass("front_card")){
		var headColor = getDecadeColor(thisCard);
	}else{
		var headColor = cardVals[indexDiff]['backgroundColor']		
	}
	//alert("animingCard animTime: " + animTime);
//alert("thisCard display: " + thisCard.css("display"));
	thisCard.animate({	"backgroundColor":headColor,
						"marginTop":cardVals[indexDiff]['marginTop'],
						"left":cardVals[indexDiff]['leftOffset'],
						"width":cardVals[indexDiff]['width'],				
						'-webkit-border-top-right-radius':cardVals[indexDiff]['cornerVal'],
						'-webkit-border-top-left-radius':cardVals[indexDiff]['cornerVal'],
						"fontSize":cardVals[indexDiff]['fontSize']},
	animTime).css({		"z-index":cardVals[indexDiff]['zIndex']	,
						'-moz-border-radius-topright':cardVals[indexDiff]['cornerVal'],
						'-moz-border-radius-topleft':cardVals[indexDiff]['cornerVal'],
						"display":"block"
				}).removeClass("behindVisible").removeClass("inFrontOfVisible");
//	thisCard.find('h2 .title, h2 .year').animate({"fontSize":cardVals[indexDiff]['fontSize']}, animTime);
//alert("exit moveCard");
}

function dropFrontCard(thisCard){
thisCard.fadeOut(animTime-200).removeClass("front_card").addClass("inFrontOfVisible");
if(thisCard.find("object").length>0){
	relVal = thisCard.attr('rel');
	replaceSwfObject(thisCard, relVal)
}
//console.log("inside dropFrontCard iterationCounter: " + iterationCounter);
}




function fadeInBackCard(indexDiffIn, thisCard){
	indexDiff = indexDiffIn-1; //decrement because we want the card to be 1 closer to the front
	setDimensions(indexDiff, thisCard);
	thisCard.removeClass("behindVisible");
return false;
}
/**
	setDimensions 
	SET (initialize) the dimensions for a single card.
	@param integer	indexDiff 	increment difference from $(this) to the front card (front card is 0, second is 1).
	@param jquery Obj	thisCard 	card to set.
	@return 						Null
*/
function setDimensions(indexDiff, thisCard){
//alert("indexDiff: " + indexDiff + "   html: " +  thisCard.html()); //IE
	var rgbVal = startRgbVal + (rgbIncr * indexDiff-1); //3 cards = 33 as increment. final card
	if(cardVals[indexDiff] == undefined){
		cardVals[indexDiff]               = [];
		rgbVal                            = (rgbVal>255)?255:rgbVal;
		var rgbStr                        = "rgb(" + rgbVal + "," + rgbVal +  "," + rgbVal + ")";
		colorPlaceHolders[indexDiff]      = rgbStr; //records gray shade order for recall later on card mouse off.
		var marginTopVal                  = maxMarginTop - (incrMarginTop * indexDiff) + Math.round(Math.pow(indexDiff,1.9));
		var leftOffsetStr                 = (incrWidth/2) * indexDiff + "px";		//take half what the width is decreasing, push off the left that much to keep centered 
		var roundCornerStr                = 15-indexDiff + "px";
		var widthVal                      = maxWidth - (incrWidth * indexDiff);
		var fontSizeStr                   = Math.round(headerMaxFontSize - (headerFontSizeIncr * indexDiff)) + "px";
		
		cardVals[indexDiff]['backgroundColor'] = rgbStr;
		cardVals[indexDiff]['marginTop']       = marginTopVal + "px";
		cardVals[indexDiff]['leftOffset']      = leftOffsetStr;
		cardVals[indexDiff]['width']           = widthVal + "px";
		cardVals[indexDiff]['cornerVal']       = roundCornerStr;
		cardVals[indexDiff]['fontSize']        = fontSizeStr;
		cardVals[indexDiff]['zIndex']          = cardsVisible - indexDiff;
	}
	thisCard.css({	"backgroundColor":cardVals[indexDiff]['backgroundColor'],
					"marginTop":cardVals[indexDiff]['marginTop'],
					"left":cardVals[indexDiff]['leftOffset'],
					"width":cardVals[indexDiff]['width'],
					'-moz-border-radius-topright':cardVals[indexDiff]['cornerVal'],
					'-moz-border-radius-topleft':cardVals[indexDiff]['cornerVal'],
					'-webkit-border-top-right-radius':cardVals[indexDiff]['cornerVal'],
					'-webkit-border-top-left-radius':cardVals[indexDiff]['cornerVal'],
					"display":"block",
					"fontSize":cardVals[indexDiff]['fontSize'],
					'z-index':cardVals[indexDiff]['zIndex']
	});
	if(indexDiff==0){		//front card
//		console.log("new front card: " + thisCard.html())
//		indexxx = $('div.card','#card_container').index($(thisCard)); //IE
//		alert("thisCard's index within its parent array: " + indexxx); //IE
//		alert("thisCard html contents in setDimensions: " + thisCard.html()); //IE
		var dColor = getDecadeColor(thisCard); //IE
		thisCard.addClass("front_card").css("backgroundColor", dColor);
	}
return false;
}

function overCard(thisCard){
	colorPlaceHolder = thisCard.css("backgroundColor");
	decadeColor = getDecadeColor(thisCard);
//console.log("decade color from overCard" + decadeColor + "  colorPlaceHolder: " + colorPlaceHolder );
	if(!thisCard.hasClass("front_card")){
		thisCard.css("backgroundColor",decadeColor);
	}
}


function offCard(thisCard, thisIndex){
	frontCardIndex = $('div.card','#card_container').index($(".front_card"));
//alert("offCard frontCardIndex: " + frontCardIndex);
	indexDiff = frontCardIndex - thisIndex;
	if(!thisCard.hasClass("front_card") && indexDiff>-1){
//		console.log("indexDiff: " + indexDiff + "  colorPlaceHolders[indexDiff]" + colorPlaceHolders[indexDiff]);
		thisCard.animate({"backgroundColor":colorPlaceHolders[indexDiff]}, colorFadeAnimTime);
	}
}

/**
	getDecadeColor
	gets the decade in the .year span, returns a color based on the decade and the colors set in the config area (top)
	@param 	Object	thisCard	jQuery object of the card div
	@return	string	color for the decade

*/
function getDecadeColor(thisCard){
//alert("# of objects passed: " + thisCard.length); //IE
//alert("# of children of that obj: " + thisCard.children().length); //IE
//alert("html content of that object: " + thisCard.html()); //IE
	decade = thisCard.find("span.year").html();
//	alert(decade); //IE
	decStr = decade.charAt(2); //IE
	decadeDigit = parseInt(decStr);
	return decColors[decadeDigit];
}

function moveStackBackward(){
//console.log("enter moveStackBackward.  frontCardIndex: " + frontCardIndex);
	animTime = animTimeRef / (iterationCounter*iterationCounter) + iterationCounter*iterationCounter;
	fadeOutBackCard($('div.card','#card_container').eq(frontCardIndex-cardsVisible+1));
	$('div.card','#card_container').each(function(){
   		var thisIndex = $('div.card','#card_container').index(this);
		indexDiff1 = frontCardIndex-thisIndex; //indexDiff1 to not collilde with indexDiff. used to calculate grayshade, size, etc.
	 		if(thisIndex <= frontCardIndex && thisIndex > (frontCardIndex - cardsVisible+1)){	//card is visible  //run moveCardBackward
				if(thisIndex == frontCardIndex){
					$(this).removeClass("front_card");
					if($(this).find("object").length>0){
						relVal = $(this).attr('rel');
						replaceSwfObject($(this), relVal);
					}
				}
				moveCard(indexDiff1, $(this), "back");
		}else if(thisIndex == (frontCardIndex+1)){//Right in front of visible.
			fadeInFrontCard($(this));
		}
	});
	iterationCounter--;
	if(iterationCounter>0){
		frontCardIndex++;
		moveStackBackward();
		return false;
	}else{	
//console.timeEnd('mouseWheel5');
		bindCardClicks();
		openCurEventLi(); //change to openCurYearLi
		activateFrontSwf();
		return false;
	}
}
function fadeInFrontCard(thisCard){
//     thisCard.css({
//        "marginTop": maxMarginTop + "px"
//        }).fadeIn(animTime+100).removeClass("inFrontOfVisible").addClass("front_card").removeClass("behindVisible"); //sm_com1
	setDimensions(0, thisCard);
	thisCard.hide().fadeIn(animTime+200);
//	thisCard.removeClass("inFrontOfVisible").addClass("front_card").removeClass("behindVisible"); //sm_com1
return false;
}

function fadeOutBackCard(thisCard){
		thisCard.css({ 
        "display": "none"
      }, animTime).addClass("behindVisible");
return false;
 }
 
function coverButtons(callback){
 	$('#coverUpDiv').fadeIn(1,callback());
 	setTimeout("uncoverButtons()",animTimeRef*3)
return false;
 }

function uncoverButtons(){
	$('#coverUpDiv').fadeOut(1);
return false;
}

function bindMousewheel(){
//	console.log("bindMousewheel in		" + new Date().getTime()/1000);
	$("*").unbind('mousewheel');
	$('div.card','#card_container').bind('mousewheel', function(event, delta){
		if(mouseWheelActive){
		mouseWheelActive = false;
			preventScrolling();
			frontCardIndex = $('div.card','#card_container').index($(".front_card"));
	//	alert("bindMousewheel frontCardIndex: " + frontCardIndex);
			iterationCounter =1;
			if(delta>.3){
				if(frontCardIndex != 0){ //don't move forward if the front card is the final card
//					console.log("delta>.3 (" + delta + ")		" + new Date().getTime()/1000 + "  mouseWheelActive: " + mouseWheelActive);
					moveStackForward();
				}
			}else if(delta<-.3){
				if(frontCardIndex != finalCardIndex){  //don't move back if the front card is the first card
//					console.log("delta<-.3 ("+delta+")			" + new Date().getTime()/1000 + "  mouseWheelActive: " + mouseWheelActive);
					moveStackBackward();
				}
			}
			setTimeout("bindMousewheel()",animTimeRef*1.1);
			setTimeout(function(){
				mouseWheelActive = true;
			}, animTime*1.1);
		}//if mousewheelactive
	});
//		console.log("bindMousewheel out		" + new Date().getTime()/1000);
return false;
}
function preventScrolling(){
	$("*").bind('mousewheel', function(event, delta){
//		console.log("preventScroll			" + new Date().getTime()/1000 + "  mouseWheelActive: " + mouseWheelActive);
		return false;
	});
return false;
}
function bindCardClicks(){
//console.time('cardClicks');  
	$('div.card','#card_container').unbind("click")
	$('div.card','#card_container').not(".front_card").bind("click", function(){
		clickedCard = this;
		coverButtons(calcForwardMotion);
	});
//	doubleCheckVisibility();
//console.timeEnd('cardClicks');
return false
}

/**
	This is to make extra sure that everything that should be visible is.
	NOT USING CURRENTLY, START USING IF PROBLEMS RETURN
*/
function doubleCheckVisibility(){	
	$('div.card','#card_container').not(".inFrontOfVisible").not(".behindVisible").css({"display":"block"});
 	setTimeout("unVisible()",animTimeRef);
	return false;
}

/**
	NOT USING CURRENTLY, START USING IF PROBLEMS RETURN
*/
function unVisible(){
	$('div.card','#card_container').filter(".inFrontOfVisible").css({"display":"none"});
	$('div.card','#card_container').filter(".behindVisible").css({"display":"none"});	
	return false;
}

/**
	get current eventNum rel value OR decade id
	@param boolean decade if true, return decade id (decade_#) instead of eventNum rel value
	@return String see above
*/
function getCurEvent(decade){
	var relVal = $('div.card','#card_container').filter(".front_card").attr("rel");
	var decadeID = $('li.decade>ul>li[rel="' + relVal + '"]','ul#TLnav').parent().parent().attr("id");
	if(decade){return decadeID;}
	else{return relVal;}
}


/////////////////////////////SWF OBJECTS//////////////////////////////////////////////
function storeSwfObjects(thisCard){
	var relVal = thisCard.attr('rel');
	swfCardContents[relVal] = $(thisCard).find('.cardContent .swfWrapper').html();
	replaceSwfObject(thisCard, relVal, true);
}
function retrieveSwfObjects(thisCard){
	var relVal = thisCard.attr('rel');
	altClass = "altContent_" + relVal;
	var flashVars = {};
	var vidPath = window["vidPath_" + relVal];
	flashVars.videoPath = vidPath;
	var attrib = {};
	attrib.id = "flashContent_" + relVal;
//	console.log("altClass: " + altClass + "  flashVars: " + flashVars);
	swfobject.embedSWF("../resources/swf/BBNVideoPlayer_r2.swf", altClass, "360", "240", " 9.0.124", "swf/expressInstall.swf", flashVars, params, attrib);
}
function replaceSwfObject(thisCard, relValIn, init){
//	alert(sm_test + "  " + init);
//	sm_test++;
	var str  = "\t\t\t<div id=\"altContent_" + relValIn + "\">\n";
	if(init){
//		alert('hello 123');
		str += "\t\t\t\t<a href=\"http://www.adobe.com/go/getflashplayer\">\n";
		str += "\t\t\t\t<img src=\"img/get_flash.png\" alt=\"Get Adobe Flash player\" />\n";
		str += "\t\t\t\t</a>\n";
	}
	str += "\t\t\t</div>\n";
//	alert(thisCard.find('.year').html() + "\n\n" + str);
	$(thisCard).find('.cardContent .swfWrapper').text("");
	$(thisCard).find('.cardContent .swfWrapper').prepend(str);
}
/**
*	This function checks if the front card is empty and loads its swf if it is
*/
function activateFrontSwf(){
//	console.log("4: ");
	if($('div.card','#card_container').filter(".front_card").find(".swfWrapper").length>0){ //content length is 0, I assume it had a video before...
		retrieveSwfObjects($('div.card','#card_container').filter(".front_card"));
	}
}
/////////////////////////////END SWF OBJECTS//////////////////////////////////////////////


/////////////////////////////TIMELINE UL//////////////////////////////////////////////
function initTimelineUl(){
	$('ul#TLnav>li.decade>ul').hide();
	curDecadeID = -1;
	openCurDecadeUl();	
////////////////setup mouseover effects for decades///////
	$('ul#TLnav>li.decade').hoverIntent(function(){
			overDecadeLi($(this));
		},
		function(){
			offDecadeLi($(this));
	});
	initYearHovers();
	//clicks
	bindTimelineLis();
}//////////initTimelineUl

function openCurEventLi(){
//alert("uno");
	var curEventRel = getCurEvent(false);
	$('li.decade>ul>li','#TLnav').each(function(){
		if($(this).attr("rel") == curEventRel){
			overYearLi($(this), true);  //force active state for current year
		}else{
			offYearLi($(this));
		}
	});
//alert("dos");
	newDecadeID= getCurEvent(true);
//alert("tres");
	if(curDecadeID != newDecadeID){
		openCurDecadeUl(newDecadeID);
	}
//alert("cuatro");
return false;
}
/**
	This function covers basically all actions that should be performed upon the changing of the decade:
		-open/close
		-add bottom border
*/

function openCurDecadeUl(newDecadeID){
	curDecadeID = newDecadeID;
	//close/open as needed
	var behindCurrent= true; //add bottom borders to decades until current is reached
	$("li.decade").each(function(){	
		if(newDecadeID == $(this).attr("id")){	
			toggleUl($(this), "open");
			$(this).css("border-bottom-style","none");
			behindCurrent = false;
		}
		else{	
			toggleUl($(this), "close");
			if(behindCurrent){ $(this).css("border-bottom","solid 1px #f1f2f4");}
			else{ $(this).css("border-bottom","none"); }
		}
	});
}

/**
	@param Object thisDecLi (jquery object) this decade li 
	@param String action open/close \
*/
function toggleUl(thisDecLi, action){
	if(action =="open" && thisDecLi.find('ul').is(":hidden")){
		thisDecLi.find('ul').slideDown(animTimeRef);
	}else if(thisDecLi.find('ul').is(":visible") && thisDecLi.attr("id") != curDecadeID){
		thisDecLi.find('ul').slideUp(animTimeRef);		
	}
return false;
}

function overDecadeLi(thisLi){
//	alert("overDecadeLi IN");
	if(thisLi.attr("id") != curDecadeID){
//	console.log("thisLi.attr(\"id\"): " + thisLi.attr("id") + "  curDecadeID: " + curDecadeID);
		toggleUl(thisLi, "open");
	}
//		alert("overDecadeLi OUT");
}
function offDecadeLi(thisLi){
//	alert("offDecadeLi   IN");
	if(thisLi.attr("id") != curDecadeID){
		toggleUl(thisLi, "close");
	}
//	alert("offDecadeLi  OUT");	
}

function bindTimelineLis(){
	$('li.decade>ul>li','#TLnav').bind('click', function(){
		var curEvent = getCurEvent(false);
		var thisEvent = $(this).attr("rel");
		var curEvNum = parseInt(curEvent.substring(9));
		var thisEvNum = parseInt(thisEvent.substring(9));
		var difference = thisEvNum - curEvNum; //positive:card is in front (future), negative:card is behind (past)
//		console.log('difference: ' + difference);
		if(Math.abs(difference) > movesThreshold){//check if |difference| is > cards visible, if so, jump closer before animating
			//get index of new card
			clickedCard = $('div.card','#card_container').filter('[rel="'+thisEvent+'"]');
			var newCardIndex = $('div.card','#card_container').index(clickedCard);
			jumpCards(newCardIndex, difference);
			return true;
		}
		if(difference != 0){
			if(difference>0){//card is in front, move back
		frontCardIndex = $('div.card','#card_container').index($(".front_card"));
//	alert("bindTimelineLis 111 frontCardIndex: " + frontCardIndex);
				iterationCounter = difference;
				moveStackBackward();
			}else{
		frontCardIndex = $('div.card','#card_container').index($(".front_card"));
//	alert("bindTimelineLis 222 frontCardIndex: " + frontCardIndex);
				iterationCounter = Math.abs(difference);
				moveStackForward();
			}
		}
	});
	
}

function jumpCards(newCardIndex, difference){	
	iterationCounter = movesThreshold;
	//figure out whether moving forward or back, adjust target index to jump to 10 in front or 10 behind newCard as needed
	if(difference>0){
		change = -movesThreshold;
		direction ="back";
	}else{
		change = movesThreshold;
		direction ="forward";
	}
	targetIndex = newCardIndex + change;
	//			alert("difference: " + difference + "  targetIndex: " + targetIndex + "  newCardIndex: " + newCardIndex);
	//pass new index to initCards to put it in the front
	initCards(targetIndex, direction);
}



/**
	setup mouseover effects for years
*/

function initYearHovers(){
//		$('li.decade>ul>li','#TLnav').hoverIntent( //try to put this back once hover stops throwing errors
	$('li.decade>ul>li','#TLnav').hover(
		function(){	
			overYearLi($(this));
		return false;
		},
		function(){	
			offYearLi($(this));
		}
	);
//alert("alpha");

	$('li.decade>ul>li','#TLnav').each(function(){
			var tooltipColor = $(this).parent().parent().css("color");
			$(this).qtip({
				content: $(this).find(".title").html(),
				show: 'mouseover',
				hide: 'mouseout',
				position: {
					corner: {
						target: 'topRight',
						tooltip: 'bottomLeft'
					}
				},
				style:{
					tip:{
						corner:'bottomLeft',
						size: {
							x: 5, 
							y : 3
						},
						color:tooltipColor
					},
					fontFamily:"arial",
					padding: 3,
					fontSize:11,
					color:"#fff",
					background: tooltipColor,
					border: "0px" 
				}
			});

	/*
	$(this).qtip({
   	content: $(this).find(".title").html(),
	   show: 'mouseover',
	   hide: 'mouseout',	
		position: {
			corner: {
				target: 'topRight',
				tooltip: 'bottomLeft'
			}
		},
		style{
			fontFamily:"arial"
		}
	})
	*/
});


	
//alert("beta");
	openCurEventLi();
//alert("gamma");
}
/**
	@param object thisLi year li to be affected
	@param bool override if true, change the color/bullet even if it's the current year
*/
//year li hover actions:
function overYearLi(thisLi, override){
	if(override == undefined){
		override=false;
	}
//alert("overYear 1");
	if(thisLi.attr("rel") == getCurEvent(false) && !override){
//		alert("overYear 2");
		return false; //do nothing if it's the current event
	}else{
//		alert("overYear 3");
		decadeColor = thisLi.parent().parent().css("color");
		thisLi.find(".century-part, .year-part").css("color",decadeColor);
		backgroundBulletName = "img/bullets/" + toRGBHex(decadeColor) + ".png";
		bgString = "url('" + backgroundBulletName + "') right center no-repeat";
				thisLi.css("background",bgString);
		//		thisLi.css("background","url('" + backgroundBulletName + "') right center no-repeat");
	}
//	alert("overYear 4");
}

/**
	@param object thisLi year li to be affected
	@param bool override if true, change the color/bullet even if it's the current year
*/
function offYearLi(thisLi, override){
//	alert("offYear 1");
	if(thisLi.attr("rel") == getCurEvent(false) && !override){
		return false; //do nothing if it's the current event
	}else{
		thisLi.find(".century-part").css("color",bgColor);
		if(thisLi.hasClass("first-of-year")){
//alert("first-of-year on: " + thisLi.html());
			thisLi.find(".year-part").css("color",inactiveColor);
		}
		else{
			thisLi.find(".year-part").css("color",bgColor);
		}
		thisLi.css("background","url('img/bullets/inactive.png') right center no-repeat");
	}
}

/////////////////////////END TIMELINE UL//////////////////////////////////////////////

function toRGBHex(num){
	if(num.indexOf('rgb')!=0){ //string is already hex (IE returns hex)
		return(num.substring(1));
	}
	num = num.substring(4).replace(/ /,"").replace(/ /,"").replace(/\)/,"");
	var decToHex="";
	var arr = new Array();
	var numStr = new String();
	numStr = num;
	
	arr = numStr.split(",");
	
	for(var i=0;i<3;i++)
	{
		var hexArray = new Array( "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" );
		var code1 = Math.floor(arr[i] / 16);var code2 = arr[i] - code1 * 16;
		decToHex += hexArray[code1];
		decToHex += hexArray[code2];
	}
	return (decToHex);
}

