
// Register the left pane state (opened/closed/expanded) with the ajax history manager:
function initLeftPaneHistory() {

	// Get the initial left pane state
	// Try it from the hash (the "bookmarked state"):
	var initialState = YAHOO.util.History.getBookmarkedState( "lpState" );
	
	if(!initialState || initialState == "") {
		// Try to get it directly from the hash:
		initialState = getParam(window.location.hash, "lpState");			
		if(!initialState) {		
			// Otherwise try it from the query string:
			initialState = YAHOO.util.History.getQueryStringParameter( "lpState" );	
			if(!initialState) {
				initialState = "open";
			}
		}		
	}
	
	// Register our "lpState" module. Module registration MUST take
	// place before calling YAHOO.util.History.initialize.

	YAHOO.util.History.register( "lpState", initialState, 
		function( paneState ) {
			// This is called after calling YAHOO.util.History.navigate, or after the user
			// has trigerred the back/forward button. We cannot discriminate between
			// these two situations.
			var xPane = getElsExpansionPane();	 
			if(xPane) {		
				xPane.openTo(paneState);	
			}
			
			// The url hash has changed - remember the current url in a cookie for
			// returning to the book player from supplemental content pages: 
			rememberCurrentBookPlayerUrl();											
		}
	);


	// Subscribe to this event before calling YAHOO.util.History.initialize,
	// or it may never get fired! Note that this is guaranteed to be fired
	// after the window's onload event.
	YAHOO.util.History.onLoadEvent.subscribe( 
		function() {
			activateLeftPane();			
		} 
	);
}

function activateLeftPane() {
 	
	// The window's onload handler is called when the user comes back to 
	// our page using the back button.
	var xPane;
	var currentState = YAHOO.util.History.getCurrentState( "lpState" );	

	// Create the pane in the initial state indicated:
	xPane = new elsExpansionPane("main", "leftContentPane", 308, currentState);		
  		  
	xPane.activatePane();		
}

// Navigate the left pane opened/closed/expanded via the ajax history manager
function navigateLeftPaneTo(state) {
	 	 
	if(state) {
		// If the Browser History Manager was not successfuly initialized,
		// the following call to YAHOO.util.History.navigate will throw an
		// exception. We need to catch it and update the UI. The only
		// problem is that this new state will not be added to the browser
		// history.
		try {
			YAHOO.util.History.navigate( "lpState", state );
		} catch ( e ) {
			var xPane = getElsExpansionPane();	 
			if(xPane) {		
				xPane.openTo(state);	
			}			
		}
	}
	// This is the fix for any state(Full-size, left-side and Hidden) change if the window gets resized
	if(typeof(sizePlayer) != 'undefined' && sizePlayer) {	 	      
		var thetimer;
		var myString = 'sizePlayer()';
		thetimer=setTimeout(myString,400);	
	}				
	return false; 
}

// Register the left pane tab module with the ajax history manager:
function initLeftPaneTabHistory() {
	// figure out which of the left pane tabs is active:
	// Try it from the hash (the "bookmarked state"):
	var initialTab = YAHOO.util.History.getBookmarkedState( "lpTab" );
		
	if(!initialTab || initialTab == "") {
		// Try to get it directly from the hash:
		initialTab = getParam(window.location.hash, "lpTab");			
		if(!initialTab) {		
			// Otherwise try it from the query string:
			initialTab = YAHOO.util.History.getQueryStringParameter( "lpTab" );	
			if(!initialTab) {
				initialTab = "contentsTab";
			}	
		}	
	}
	
	// Register our "lpTab" module. Module registration MUST take
	// place before calling YAHOO.util.History.initialize.
	
	YAHOO.util.History.register( "lpTab", initialTab, 
		function( tabState ) {		
			// This is called after calling YAHOO.util.History.navigate, or after the user
			// has trigerred the back/forward button. We cannot discrminate between
			// these two situations.
			activateTab("leftPaneTabs", tabState); 
			
			// The url hash has changed - remember the current url in a cookie for
			// returning to the book player from supplemental content pages: 
			rememberCurrentBookPlayerUrl();							
		}
	);


	// Subscribe to this event before calling YAHOO.util.History.initialize,
	// or it may never get fired! Note that this is guaranteed to be fired
	// after the window's onload event.
	YAHOO.util.History.onLoadEvent.subscribe( 
		function() {
			activateLeftPaneTabs();			
		} 
	);
}

function activateLeftPaneTabs() {
	// The window's onload handler is called when the user comes back to 
	// our page using the back button.
	
	// Get the div tag surrounding the right hand side content:		
	var leftPaneTabsAreaElement = dojo.byId("leftPaneTabs");
	
	// Have we already activated?
	if(leftPaneTabsAreaElement && leftPaneTabsAreaElement.activated) {
		// Yup - don't do it twice!
		return;
	}		
	
	// Remember that we've activated:		
	leftPaneTabsAreaElement.activated = true;
	
	var leftPaneTabs;
	var currentTab = YAHOO.util.History.getCurrentState( "lpTab" );	
	if (currentTab) {
		// Create the tabs making this tab initially active:
    	leftPaneTabs = new elsSmartTabs('leftPaneTabs', currentTab); 		
	}
	else
	{
		// Create the tabs using the cookie to know which is active:
    	leftPaneTabs = new elsSmartTabs('leftPaneTabs'); 
    }
  
	leftPaneTabs.onSelect = leftPaneTabSelected;
	leftPaneTabs.onChange = leftPaneTabChanged;			  
    leftPaneTabs.activateTabs();	
}

// Activate the specified tab in the specified dojo tab container,
// and remember which is active in a cookie.
function activateTab(tabContainerId, tabName) {
	if(tabContainerId && tabName && tabName != "") {
		var tabContainerElem = dojo.byId(tabContainerId);
		if(tabContainerElem) {
			var smartTabs = tabContainerElem.smartTabs;
			
			// Due to what appears to be some kind of race condition(?)
			// in IE, sometimes we don't get the smartTabs if we've left
			// the book player and come back into it - so here we have 
			// a workaround where we re-initialize the tabs if that happens:
			// (I say "race condition" because another fix was to simply 
			// add an alert box in activateLeftPaneTabs
			if(!smartTabs) {
				activateLeftPaneTabs();
				smartTabs = tabContainerElem.smartTabs;				
			}
			
			if(smartTabs) {
				smartTabs.activateTab(tabName);
			}			
		}		
	}
}

// Handle when the user selects a tab
function leftPaneTabSelected(selectChildEvt, smartTabs, selectedTab, tabElement) {
	
	// If we try and use Yahoo history manager to navigate the index tab
	// forward it breaks the dojo LinkPanes! 
	if(selectedTab != "indexTab") {
		// If the Browser History Manager was not successfuly initialized,
		// the following call to YAHOO.util.History.navigate will throw an
		// exception. We need to catch it and update the UI. The only
		// problem is that this new state will not be added to the browser
		// history.
		try {
			YAHOO.util.History.navigate( "lpTab", selectedTab );
		} catch ( e ) {
			smartTabs.activateTab(selectedTab);				
		}
	}
			
	return false; 
}

// Respond to when the active tab has changed
function leftPaneTabChanged(leftPaneSmartTabs, selectedTab) {	 
	if(selectedTab && selectedTab == "contentsTab") {

		if(gLeftPaneTree && gLeftPaneTreeSelectedLi) {
			gLeftPaneTree.tocReloaded = true;	// make it jump not scroll	
			tocSelectionChanged(gLeftPaneTree, gLeftPaneTreeSelectedLi);			
		}	
	}
}


// Pre-process one of the anchor tags for a node of the contents tree,
// in preparation for the "tocAnchorSelected" call (which follows below).
function tocAnchorPreProcess(anchorTag) { 
	var href = anchorTag.href;
	var eid = getQueryParam(href, 'eid', '');
	var isbn = getQueryParam(href, 'isbn', '');
	var type = getQueryParam(href, 'type', 'bookPage');	
	anchorTag.isbn = isbn;
	anchorTag.eid = eid;
	// To follow the linkTo url type should be either bookPage or figurePage. Here left side toc type is bookPage.
	anchorTag.type = type;
	// Make it so we never follow the original href... 
	//anchorTag.href = "#";

	// Do they want to show the eids in the toc?
	// (this has been added to allow admins to see their eids)
	if(typeof(showTocEIDs) != 'undefined' && showTocEIDs) {		
		// Is this the TOC node for one of the free sections?
		// Note:  There are documented performance issues with looping through
		//        large javascript arrays in some browsers.  Searching as a 
		//        string here is a performance optimization.  Note that we 
		//        include the comma to ensure that it truly is the entire eid
		//        being matched (not a shorter eid matching the beginning of a
		//        longer one).  We've added a comma on the end of dartTocTargetStr 
		//        to ensure this heuristic even works for the last toc target eid.
		
		// Insert the "Free!" icon in the body of the anchor (so it's clickable!):
		var anchorTagParent = anchorTag.parentNode;								
		var firstChild = anchorTagParent.firstChild;
		if(firstChild) {			
			var tocEid = document.createElement('SPAN');
			tocEid.innerHTML = eid + '</br>';
			tocEid.className = "tocEidDisplay";		
			tocEid.border = 0;
			anchorTagParent.insertBefore(tocEid,firstChild);
		}				
	}

	// If the toc eids where updates have been applied is available...
	// And a icon has been defined for showing it in the TOC:
	if(typeof(dartTocTargetsStr) != 'undefined' && dartTocTargetsStr &&
		typeof(tocUpdateIndicatorIcon) != 'undefined' && tocUpdateIndicatorIcon	
	) {		
		// Is this the TOC node for one of the updated sections?
		// Note:  There are documented performance issues with looping through
		//        large javascript arrays in some browsers.  Searching as a 
		//        string here is a performance optimization.  Note that we 
		//        include the comma to ensure that it truly is the entire eid
		//        being matched (not a shorter eid matching the beginning of a
		//        longer one).  We've added a comma on the end of dartTocTargetStr 
		//        to ensure this heuristic even works for the last toc target eid.
		if(dartTocTargetsStr.search(eid + ',') >= 0) {
			// Insert the "Updated" icon in the body of the anchor (so it's clickable!):								
			var firstChild = anchorTag.firstChild;
			if(firstChild) {			
				var updatedIcon = document.createElement('IMG');
				updatedIcon.src = tocUpdateIndicatorIcon;
				updatedIcon.className = "tocUpdateIndicator";		
				updatedIcon.border = 0;
				anchorTag.insertBefore(updatedIcon,firstChild);
			}				
		}
	}	
	
	var freeEidPatterns=["cebib","fread","ref","biblio","fur"];
	// If the free toc eids are available...
	// And a icon has been defined for showing them in the TOC:
	if(typeof(freeTocTargetsStr) != 'undefined' && freeTocTargetsStr &&
		typeof(tocFreeIndicatorIcon) != 'undefined' && tocFreeIndicatorIcon	
	) {		
		// Is this the TOC node for one of the free sections?
		// Note:  There are documented performance issues with looping through
		//        large javascript arrays in some browsers.  Searching as a 
		//        string here is a performance optimization.  Note that we 
		//        include the comma to ensure that it truly is the entire eid
		//        being matched (not a shorter eid matching the beginning of a
		//        longer one).  We've added a comma on the end of dartTocTargetStr 
		//        to ensure this heuristic even works for the last toc target eid.
		if(freeTocTargetsStr.search(eid + ',') >= 0) {
			// Insert the "Free!" icon in the body of the anchor (so it's clickable!):								
			var firstChild = anchorTag.firstChild;
			if(firstChild) {			
				var freeIcon = document.createElement('IMG');
				freeIcon.src = tocFreeIndicatorIcon;
				freeIcon.className = "tocFreeIndicator";		
				freeIcon.border = 0;
				anchorTag.insertBefore(freeIcon,firstChild);
			}	
		}
		else{
			
			for(var i=0;i<freeEidPatterns.length; i++) {
			
				if((eid.indexOf(freeEidPatterns[i]) != -1)) {
					var firstChild = anchorTag.firstChild;
					if(firstChild) {			
					var freeIcon = document.createElement('IMG');
					freeIcon.src = tocFreeIndicatorIcon;
					freeIcon.className = "tocFreeIndicator";		
					freeIcon.border = 0;
					anchorTag.insertBefore(freeIcon,firstChild);
			}	
		}
		}
		}
	}			
}

// Handle a selection made on a node of the contents tree
function tocAnchorSelected(evt, tree, treeNodeId, anchorTag) {
	 
	if(anchorTag.eid) {

		var currentlyDisplayedEid = getCurrentEid();
		var contentState = anchorTag.eid + ';from=toc' + ';' + "type="+anchorTag.type + ';' + "isbn="+anchorTag.isbn;	
		if(anchorTag.eid != currentlyDisplayedEid) {	
			// If the Browser History Manager was not successfuly initialized,
			// the following call to YAHOO.util.History.navigate will throw an
			// exception. We need to catch it and update the UI. The only
			// problem is that this new state will not be added to the browser
			// history.
			try {				
				YAHOO.util.History.navigate( "content", contentState );
			} catch ( e ) {
				updateContentArea("bookContentPane", contentState); 		
			}
		}
		else {	
			// The nature of the Ajax history manager is to respond to changes
			// in the hash.  In this case the hash doesn't change and therefore
			// updateContentArea doesn't get called.  The problem is that
			// updateContentArea also does things like unexpand the left
			// pane, so without the following the left pane doesn't unexpand
			// if they click on the toc entry for the *currently* displayed
			// item:
			updateContentArea("bookContentPane", contentState);			
		}
	}
			
	return false; 
}

// Animate a smooth scroll to the highlighted element within the toc
// This is registered as an "onSelectionChange" callback for the tocTree	

// THE FOLLOWING ARE TEMPORARY TRYING TO SYNC THE SCROLL POSITION OF THE TOC TAB QUICK & DIRTY:
// THESE ARE USED IN leftPaneTabChanged
var gLeftPaneTree;
var gLeftPaneTreeSelectedLi;
		
function tocSelectionChanged(tree, li) {

	// This is the TOC's scrolling div area:
	var tocAreaElement = dojo.byId("contentsTab");

	if(li && tocAreaElement) {

gLeftPaneTree = tree;
gLeftPaneTreeSelectedLi = li;

        // Have we just finished loading/reloading the TOC from the server?:
        var tocReloaded = tree.tocReloaded;
		tree.tocReloaded = false;  	
	
		var liPosition = tocScrollTopLIPosition(li, tocAreaElement);
		
		// If it's in the top two thirds of the scrolling div:
		if(liPosition >= tocAreaElement.scrollTop &&
			(liPosition - tocAreaElement.scrollTop) <= (2 * tocAreaElement.clientHeight / 3)) {
				// let's not get animation-happy it's too distracting:
				return;
		} 		
							
		// But otherwise let's try and keep the selected item part-way down
		// so the user can see the context of where they're at in the TOC:
		var targetTop = liPosition - (tocAreaElement.clientHeight / 3);
		if(targetTop <= 0) {
			targetTop = 0;
		}		
							
		// But don't waste time/resources animating for no reason!
		// (the tree sometimes highlights the same item more than once)
		if(targetTop == tocAreaElement.scrollTop) {
			return;
		}							
		
		// It's annoying to animate the scroll when they just finished 
		// seeing a "Loading..." spinner:
		if(tocReloaded) {
			// So just jump in that case
			tocAreaElement.scrollTop = targetTop;
		}
		else
		{
			// But otherwise animating is good so it's clear to them what's happened:
			var scrollAnim = new dojo.lfx.Animation({  
			             onAnimate: function(value){ 
			             	if(this.tocAreaElement) {
			                     this.tocAreaElement.scrollTop = value;
							}
			             } 
			     }, 
			     1000,  
			     [tocAreaElement.scrollTop, targetTop],
			     dojo.lfx.easeInOut 
			);
	
	        if(scrollAnim) {
	        	// Make the contentArea available to the onAnimation handler:
	        	scrollAnim.tocAreaElement = tocAreaElement;
	        	scrollAnim.play();
	        }        
        }
	}
}

// Get the position of the specified li within the TOC area
// (i.e. what would the div tag's scrollTop be if the li were at the top) 
function tocScrollTopLIPosition(li, tocArea) {
	
	var targetTop = 0;
	
	if(li) {
		
		var tocAreaPos = dojo.html.getAbsolutePosition(tocArea,true,dojo.html.boxSizing.BORDER_BOX);
		var liPos = dojo.html.getAbsolutePosition(li,true,dojo.html.boxSizing.BORDER_BOX);	
						 
		// Need the relative offset between the two (these are absolute to the browser as a whole):
		var targetTop = liPos.top - tocAreaPos.top;
		
		// For Mozilla there's some kind of fudge factor going on (not sure why): 	
		if (dojo.render.html.moz) {			
			targetTop -= 20;
		}
						
	}
	
	// In IE, what we've just computed is not the actual target, but the
	// difference between what the target currently is and what it *should* be:
	if (dojo.render.html.ie) {
		targetTop = tocArea.scrollTop + targetTop;				
	}		
			
	return targetTop;
}		

//
// Note: we found in the true A&E/eRights environment, the redirect for
//       login was causing errors that were not predictable, so we've
//       added our own inactivity timeout that should prevent this
//       method from even seeing the login error here.  For now I'm
//       leaving it below but it may be able to be removed in the 
//       future (don't have time to restest such a change right now).
// 
function tocCheckForAjaxError(data, tree, li) {

	// Is this the building blocks error page: 
	var bbErrorPage = parseAttributeValue(data, "meta", "content", "name", "BB.errorCode"); 
	if(bbErrorPage) {
		return true;
	}
	
	// We've included a meta tag in the full page payloads indicating the kind of response: 
	var pageType = parseAttributeValue(data, "meta", "content", "name", "elsPageType"); 
	if(!pageType) {
		// It seems the redirect for login appears as a 302 page instead of
		// truly redirecting and causing ajax to see the login page - at least
		// in some (if not all) circumstances:
		if (data.indexOf('302') != -1) {
		
			// We get a page with:
			//	 "The document has moved <a href="http://[ssoHost]/epp/ae/sso/subsidiaryLogon[...]">here</a>
			// (but try and be a little robust in case that should change slightly)
			if(data.indexOf('login') != -1 ||
				data.indexOf('Login') != -1 ||
				data.indexOf('logon') != -1 ||
				data.indexOf('Logon') != -1) {
					pageType = "login";
			}
			
			// It doesn't appear upsells have the same issue but JIC:
			if(data.indexOf('upsell') != -1 ||
				data.indexOf('Upsell') != -1) {
					pageType = "upsell";
			}			
			
		}	
	}		
	
	if(pageType) {
		// We can get a login page if their session has timed out: 
		if(pageType == "login") {
			reloginUser();		
			return true;	
		}
	
		if(pageType == "upsell") {
			// This should never happen because the book player won't come up to begin
			// with if they don't have access - but if it did don't show the upsell page
			// in the tree (that's ridiculous):
			alert("You're attempting to access premium content from a basic account.");	
						
			return true;
		}
	}
	
	return false;
}



// Activate the Index tab's A-Z link's "smart tabs":
// Note:  This is only called after the LinkPane loads the A-Z links/tabs.
function initIndexAZLinkTabs() {
	// Create and activate the index tabs/links, which are
	// currently loaded dynamically via a Dojo LinkPane:
	var azTabs = new elsSmartTabs('indexLetters');			
	if(typeof(isbn) != 'undefined' && isbn){		
	   	azTabs.cookieName = 'SelectedLetter'+isbn;	
	} else {
		azTabs.cookieName = 'SelectedLetter';
	}
	azTabs.activateTabs();	
}	

function initActivateLeftPaneAndTabs() {
	if(typeof(yahooHistoryInitialized)!= 'undefined' && yahooHistoryInitialized) {
	    activateLeftPane();
	    activateLeftPaneTabs();
	 } else {
		 setTimeout('initActivateLeftPaneAndTabs();', 300);
	 }   
}

dojo.addOnLoad(initActivateLeftPaneAndTabs);
