//aotf js.  load jquery first

var figIndexSelected = 0;
var contextInArticleSelected = false;
var contextInArticleText = "";
var contextInSecondSubTabIndex = 0;
var searchterm = "";
var searchmode = false;

//This method is called once on fulltext page load.
function renderTabContentsWithDwr() {		
	$(document).ready(function(){	
	
	// Initialize history plugin.
	// The callback is called at once by present location.hash.
	$.historyInit(setupTab);
	// set onlick event for buttons and also set tabs...
	$("a[rel='history']").click(function(){
		var hash = this.href;
		var articlePII = getArticlePII();
		hash = hash.replace(/^.*#/, '');
		// for hiding references popups when another tab is clicked
		$("#popup_ref").hide(); 
		// moves to a new page.
		// pageload is called at once.
		// hash don't contain "#", "?"
		$.historyLoad(hash);
		_gaq.push(["_trackEvent", "AOTF-TabClick", hash, articlePII]); 
		$("ul#aotftabs li").removeClass("active"); 
		$(this).parent().addClass("active"); 
		return false;
	});
	
	//for global nav, set up hover dropdown and change ajaxcontainer to static
	//to avoid IE7 bug
	$("#nav li").mouseenter(
		function(){
			$(this).addClass("over");
		}).mouseleave(
		function(){
			$(this).removeClass("over");
	});
	
	$(window).resize(function() {
		setAOTFADheight();	
		if ($("#resultssplitter").length) {
			$("#resultssplitter").trigger("resize");
		}
		if ($("#zoomfigure").length) {
			changeSource(changeSource_id,changeSource_source) ;
		}
		setLoadHeight();
	});
	
	//For Search term
	$('#findterm').click(function(){
		$('#findterm').val('');
		$('#findtermerror').hide();
	});
					   
	$('#findtermbutton').click(function(){
		findSearchTermInArticle();
	});

	$('#removetermbutton').click(function(){
		$('#findtermerror').hide();
		$('#findterm').val('');
		$('#load').removeHighlight();
		$(".termcount").remove();
		searchtext = "";
		searchmode = false;
	});

	 // Reflect onselect checkbox events
     $("input[type=checkbox][name=proteins]").click(function(){  
        // If checked
        if (!checkIfProteinCheckboxIsNotSelected())  {
              $('span.reflect_protein').attr('style','background-color: rgb(204, 255, 255) ! important;');
			  $('span.reflect_ambigous').attr('style','background-color: rgb(204, 255, 255) ! important;');
        }
        else {     
           $('span.reflect_protein').removeAttr("style");
		   $('span.reflect_ambigous').removeAttr("style");
        }
      });

	  $("input[type=checkbox][name=chemicals]").click(function(){  
        if (!checkIfChemicalCheckboxIsNotSelected()) {
              $('span.reflect_chemical').attr('style','background-color: rgb(204, 255, 255) ! important;');
			  $('span.reflect_ambigous').attr('style','background-color: rgb(204, 255, 255) ! important;');
        }
        else {     
           $('span.reflect_chemical').removeAttr("style");
		   $('span.reflect_ambigous').removeAttr("style");
        }
      });
	});
	}	

// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser
function setupTab(hash) {
	
	//Handle Problems in rendering comments tab in Safari - False Call - From JSKit - Skip the switching of tabs.
	//Attention!! - Please don't refactor this piece from here or it wouldn't work.
	if(is_nav) {
		if(arguments.callee.caller.toString().toLowerCase().indexOf('function ()') == 0) {
			return;
		}
	}
	
	removeVideoObjectOnTabSwitch();

	// hash doesn't contain the first # character.
	if (hash) {
		// restore ajax loaded state
		// $("#load").load(hash + ".html");
		$("#ajaxanim").show();
		$("#popup_ref").hide(); 
		var aotf_article_pii = getArticlePII();
		var is_abstractPage = $("#aotf_summary").html();
		switchTab(aotf_article_pii, hash, is_abstractPage);
		$("ul.backtabs li").removeClass("active"); // Remove any "active" class
		$("ul.backtabs li a").attr("href");
		$("a[href='#" +hash+ "']").parent().addClass("active");
	} else {
		var aotf_article_pii = getArticlePII();
		$("#ajaxanim").show();
		var firstTabName= $(".ajaxcontainer ul.backtabs li:eq(0) a span").html();
		if(firstTabName == null)
		firstTabName= $(".ajaxcontainer ul.backtabs li:eq(1) a span").html();
		var is_abstractPage = $("#aotf_summary").html();
		switchTab(aotf_article_pii, firstTabName, is_abstractPage);
		// start page
		//$("#load").empty();
	}
}

//Remove Video Object From Summary Tab after Tab Switch
function removeVideoObjectOnTabSwitch() {
	if($('#videoPlayerHolder').length > 0) {
		$('#videoPlayerHolder').remove();
	}
}

// set up caption/context tabs
function setupCaptionAndContextInFiguresTabToggle() {
	$(".figdetails ul.backtabs li").click(function() {
		thisid = $(this).attr('id');
		$("#popup_ref").hide();
		$(".figdetails ul.backtabs li").removeClass("active");
		$(this).addClass("active");
		$('.detailstoggle').hide();
		$('#details_' + thisid).show();
		var aotf_figure_id = $(".figureTextHighlighting")[0].innerHTML;
		markWords(aotf_figure_id, 'details_context');
		if (document.all)
		{
			setUpPopUpReferencesOnTextSubTabForIE();
		}else{
			setUpPopUpReferencesOnTextSubTab();
		}
		return false;
	});
}

function showAotfContent() {
	$('#aotfContentWhenJSisOn').show();
}

function activate_affils() {		
	//hover over authors to find affiliations					   
	$("#authorslist").find("a.author").hover(
		  function () {
			var supstring= this.getAttribute("aff");
			var thisauthorArray = [];
			thisauthorArray =supstring.split(',');
			//console.log("auth"+thisauthorArray);
			$(this).addClass("hiliter");
			jQuery.each(thisauthorArray, function(index, value) {
				//console.log("index", index, "value", value);
				$("#affiliations").find("#" +value).addClass("hiliter");
			});
	
		  }, 
		  function () {
			$("#affiliations").find("a").removeClass("hiliter");
			$(this).removeClass("hiliter");
		  }
    );

	//hover over affiliations to find authors			
	$("#affiliations").find("a.affil").hover(
		  function () {
			//var affnum= $(this).find("sup").html();
			var affnum = this.getAttribute("id");
			$(this).addClass("hiliter");
			
			$("#authorslist").find(".author").each(function(i) {
				var thisauthor = $(this);											
				//var authhtml = $(this).find("sup").html();		
				var authhtml = this.getAttribute("aff");
				authoraffils = authhtml.split(",");
				//console.log("aff"+authoraffils);
				jQuery.each(authoraffils, function(index, value) {
					//console.log(affnum, "index", index, "value", value);
					if (value == affnum) {
						$(thisauthor).addClass("hiliter");
					}
				});
			});
		  }, 
		  
		  function () {
			$("#affiliations").find("a").removeClass("hiliter");
			$("#authorslist").find(".author").removeClass("hiliter");
		  }
    );
} //activate

function deactivate_affils() {		
	//hover over authors to find affiliations					   
	$("#authorslist").find("a.author").hover(
		  function () {
			$("#affiliations").find("a").removeClass("hiliter");
			$(this).removeClass("hiliter");
		  }
    );
} //deactivate



//Results tab

var imgratio=0;

var hfig;
var changeSource_id;
var changeSource_source;
var scalefactor100;
var figdetail_h;
function changeSource(id,source) {
	changeSource_id = id;
	changeSource_source = source;
	function returnGetElement(v) {return document.getElementById(v);}; //don't use jquery!! use old-fashioned JS for image scaling
	$("#tablediv").hide();
	$("#videodiv").hide();
	$("#zoomfigure").show();
	$("#highquality").show();
	$("#showcaption").show();
	$("#slider-container").show();
	
	var img=new Image();
	img.onload=function() {
	
		ele=returnGetElement(id);    
		imgratio = img.width/img.height;
		var figimg_w = img.width;
		var figimg_h = img.height;	//
		
		//this sizes img to #figuredetail
		$("#zoomfigure").height($("#figuredetails").height()-100);
		ele.style.height = ($("#figuredetails").height()-100) +'px';  //was .91 JJ 6/20/2011
		//ele.style.height = (figdetail_h * .8)+'px';  //was .91 JJ 6/20/2011
		scalefactor= parseInt(ele.style.height)/img.height;
		ele.style.width = (img.width*scalefactor)+'px';
		
		if (parseInt(ele.style.width) > (figdetail_w *.94)) {   //was .98
			//alert("wide");
			ele.style.width = (figdetail_w *.94)+'px';
			scalefactor = (figdetail_w *.94)/img.width;
			ele.style.height = (img.height*scalefactor)+'px';
		}
		scalefactor100 = Math.round(scalefactor * 100);
		$("#slider").slider( "option", "value", scalefactor100 );
		$("#slider-amount").val(scalefactor100 +"%");  //format me
		
		//limit to 100% 
		if (scalefactor100 > 100) { 
			$("#slider-amount").val("100%");
			$("#zoomtarget").css({"width":img.width,"height":img.height})
		}
	    ele.src=img.src;
	};
	img.src=source;	
	$("#zoomtarget").draggable(); 
}

function showTableAndHideZoomFigure() {
	$("#zoomcaption").hide();
	$("#zoomfigure").hide();
	$("#tablediv").show();
	$("#zoomhints").hide();
	$("#highquality").hide();
}	


function showTip(srcObject, tipText){
    tipobj = document.getElementById('toolbartips');
    tipobj.innerHTML = tipText;
    tipobj.style.display = 'block';
	tipobj.style.left = (getPosition(srcObject)[0] - 30) + 'px';
	tipobj.style.top = (getPosition(srcObject)[1] - 15) + 'px';

}
function hideTip(){
    tipobj = document.getElementById('toolbartips');
    tipobj.style.display = 'none';
}

function markWords(jmjWord, jmjSrcId){
	jmjWord = jmjWord.replace(/(\s|&nbsp;)+/g, ' ');
	var jmjWordPart2 = jmjWord.split(' ')[1];
	if (jmjWordPart2.charAt(jmjWordPart2.length - 1) == '.') {
		jmjWordPart2 = jmjWordPart2.substr(0, jmjWordPart2.length - 1);
	}
	var regexpstr = "(" + jmjWord.split(' ')[0] + "s{0,1} " + jmjWordPart2 + ")";
	var re = new RegExp(regexpstr,'ig');
	var histr = '<span class="hgl">$1</span>';
	searchSrc = document.getElementById(jmjSrcId).getElementsByTagName('li');
	for (srcIndex=0; srcIndex<searchSrc.length; srcIndex++){
		var olstr = searchSrc[srcIndex].innerHTML;
		olstr = olstr.replace(/(\s|&nbsp;)+/g, ' ');
		var newstr = olstr.replace(re, histr);
		searchSrc[srcIndex].innerHTML = newstr;
	}
}

function highlightContext(contextTextToHigh){
	//hide all existing higlights on the div - useful in case of self tab references.
	$('.hgl').removeAttr('style');
	$('.hgl').removeAttr('class');
	//Changing the innerHtml of Load to highlight the matched text.
	var numberOfSubtabs = $('div#load div.intro-reftoggle') ;
	if(	numberOfSubtabs.length == 0) {
		numberOfSubtabs = $('div#load') ;
	}
	for (subtabctr=0; subtabctr < numberOfSubtabs.length; subtabctr++)
	{
		if(	numberOfSubtabs.length == 1) {
			var contextSentences = $('div#load').html().split(/\.\s|\.<\w*\/\w*>|\.\s*\n/);
		} else {
			var contextSentences = $('div#load div.intro-reftoggle:eq('+ subtabctr + ')').html().split(/\.\s|\.<\w*\/\w*>|\.\s*\n/);
		}
		for ( var i = 0; i < contextSentences.length; i++ )
		{
			if( (contextSentences[i].replace(/<\/?[^>]+>/gi, '') + ".").indexOf(contextTextToHigh.replace(/<\/?[^>]+>/gi, '')) > -1) {
				//First Sentence of a new para or list item is a special case - hence treated separately
				if( i==0 || contextSentences[i].indexOf('<') >= 0 ) {
					contextSentences[i] = contextSentences[i].substr(contextSentences[i].indexOf(contextTextToHigh.replace(/<\/?[^>]+>/gi, '').substr(0,5)));
				}
				var highlightedText = '<span class="hgl">' + contextSentences[i] + '</span>';
				$('#load').html($('#load').html().replace(contextSentences[i], highlightedText));
				contextInSecondSubTabIndex=subtabctr;
				break;
			}
		}
	}
	if(contextInSecondSubTabIndex > 0) {
		setSwitchingofHighlightedSubtab($(".tabContent ul.backtabs li")[contextInSecondSubTabIndex]);
	}
	contextInArticleSelected = false;
	var hobj = $(".hgl")[0];
	if( hobj != 'undefined'){
		hobj.scrollIntoView(true);
	}
	$(".hgl").animate({ backgroundColor:"#FFFFFF" }, 12000, "linear", makehightran);
}

function highlightResultsContext(contextTextToHigh){
	//hide all existing higlights on the div - useful in case of self tab references.
	$('.hgl').removeAttr('style');
	$('.hgl').removeAttr('class');
	//Changing the innerHtml of div#outlinelist to highlight the matched text.
		var zoomResultsDiv = $('div#outlinelist') ;
		var contextSentences = $('div#outlinelist').html().split(/\.\s|\.<\w*\/\w*>|\.\s*\n/);
		for ( var i = 0; i < contextSentences.length; i++ )
		{
			if( (contextSentences[i].replace(/<\/?[^>]+>/gi, '') + ".").indexOf(contextTextToHigh.replace(/<\/?[^>]+>/gi, '')) > -1) {
				//First Sentence of a new para or list item is a special case - hence treated separately
				if( i==0 || contextSentences[i].indexOf('<') >= 0 ) {
					contextSentences[i] = contextSentences[i].substr(contextSentences[i].indexOf(contextTextToHigh.replace(/<\/?[^>]+>/gi, '').substr(0,5)));
				}
				var highlightedText = '<span class="hgl">' + contextSentences[i] + '</span>';
				$('div#outlinelist').html($('div#outlinelist').html().replace(contextSentences[i], highlightedText));
				break;
			}
		}

	// start - for collapsible panel in the results tab
	var collapsiblePanelObj = $('.CollapsiblePanel')[0];
	if (collapsiblePanelObj) {
		var	collapsiblePanelObjId = collapsiblePanelObj.id;
		var CollapsiblePanel = new Spry.Widget.CollapsiblePanel(collapsiblePanelObjId);
	    CollapsiblePanel.close();
	}	
    // end - collapsible panel
    
	contextInArticleSelected = false;
	var hobj = $(".hgl")[0];
	if( hobj != 'undefined') {
		hobj.scrollIntoView(true);
		if (document.all) {
			// hack needed for IE7 only
			hobj.scrollIntoView(true);
		}
	}	
	$(".hgl").animate({ backgroundColor:"#FFFFFF" }, 12000, "linear", makehightran);
}

function makehightran(){
	var cssObj = {'background-color' : 'transparent'};
	$(".hgl").css(cssObj);
}

var contextMenuObj ='';
function showContextMenu(contextObj){
	if (contextMenuObj) hideContextMenu();
	contextMenuObj = contextObj.parentNode.parentNode.nextSibling;
	contextMenuObj.style.display = 'block';
}
function hideContextMenu(){
	contextMenuObj.style.display = 'none';
}

// References Filtering Widget
var currentYearItem='';
var jmjYearCellValues = new Array();
var jmjYearCounts = new Array();
var jmjYearItems = new Array();
var yearTableObjectRows;

function creatYearGraph(){
	yearTableObject = document.getElementById("refs_table");
	yearTableObjectRows = yearTableObject.getElementsByTagName("TR");
	jmjYearCellValues = [];
	for (ytrows=1; ytrows<yearTableObjectRows.length; ytrows++){
		yearTableObjectCells = yearTableObjectRows[ytrows].getElementsByTagName("TD");
		jmjYearCellValues.push(yearTableObjectCells[1].innerHTML);
	}
	jmjYearCellValues.sort();
	for (ycv=0; ycv<jmjYearCellValues.length; ycv++){
		jmjYearCounts[parseInt(jmjYearCellValues[ycv])] = 0;
	}
	for (ycv=0; ycv<jmjYearCellValues.length; ycv++){
		jmjYearCounts[parseInt(jmjYearCellValues[ycv])] = (jmjYearCounts[parseInt(jmjYearCellValues[ycv])])?(jmjYearCounts[parseInt(jmjYearCellValues[ycv])] + 1):1;
	}
	
	yearGraphObject = document.getElementById('yeargraph');
	yearGraphItems = yearGraphObject.getElementsByTagName('li');
	var yearIdctr=1960;
	for (graphItemsIndex=0; graphItemsIndex<yearGraphItems.length; graphItemsIndex++){
		if ((yearGraphItems[graphItemsIndex].className != 'decadeLine') && (yearGraphItems[graphItemsIndex].className != 'label')){
			yearGraphItems[graphItemsIndex].id="Y" + String(yearIdctr) + ":" + String(jmjYearCounts[yearIdctr]);
			if (jmjYearCounts[yearIdctr]){				
				yearGraphItems[graphItemsIndex].style.height = jmjYearCounts[yearIdctr]*2 + "px";
				yearGraphItems[graphItemsIndex].style.marginTop = (30 - jmjYearCounts[yearIdctr]*2) + "px";

(document.all)?yearGraphItems[graphItemsIndex].attachEvent('onclick',filterByYear):yearGraphItems[graphItemsIndex].addEventListener('click',filterByYear,false);
(document.all)?yearGraphItems[graphItemsIndex].attachEvent('onmouseover',highlightYear):yearGraphItems[graphItemsIndex].addEventListener('mouseover',highlightYear,false);
(document.all)?yearGraphItems[graphItemsIndex].attachEvent('onmouseout',lowlightYear):yearGraphItems[graphItemsIndex].addEventListener('mouseout',lowlightYear,false);
				jmjYearItems.push(yearGraphItems[graphItemsIndex]);
			} else{
				yearGraphItems[graphItemsIndex].style.height = "10px";
				yearGraphItems[graphItemsIndex].style.backgroundColor = "transparent";
			}
				yearIdctr++;
		}			
	}
}
function filterByYear(e){
	var yearItem;
	if (!e) var e = window.event;
	if (e.target) yearItem = e.target;
	else if (e.srcElement) yearItem = e.srcElement;
	if (yearItem.nodeType == 3) yearItem = yearItem.parentNode;
	yearItem.style.backgroundColor = "#e70909";
	if (currentYearItem){
		currentYearItem.style.backgroundColor = "#039";
		currentYearItem = yearItem;
	}else{
		currentYearItem = yearItem;
	}
	for (ytrows=1; ytrows<yearTableObjectRows.length; ytrows++){
		yearTableObjectCells = yearTableObjectRows[ytrows].getElementsByTagName("TD");
		yearTableObjectRows[ytrows].style.display = (('Y'+yearTableObjectCells[1].innerHTML) == yearItem.id.split(':')[0])?'':'none';
	}
	$("#allYears").show();
	hideTip();
	$("#currYrCnt").html(yearItem.id.split(':')[0].split('Y')[1] + " (" + yearItem.id.split(':')[1] + ")");
	hideauthormenu();
	document.getElementById("trigAllAuth").style.display="none";
}
function showAllYears(){
	for (ytrows=1; ytrows<yearTableObjectRows.length; ytrows++){
		yearTableObjectRows[ytrows].style.display = '';
	}
	$("#allYears").hide();
	$("#currYrCnt").html('');
	for (graphItemsIndex=0; graphItemsIndex<jmjYearItems.length; graphItemsIndex++){
		jmjYearItems[graphItemsIndex].style.backgroundColor = "#039";
	}
	
}
function highlightYear(e){
	var yearItem;
	if (!e) var e = window.event;
	if (e.target) yearItem = e.target;
	else if (e.srcElement) yearItem = e.srcElement;
	if (yearItem.nodeType == 3) yearItem = yearItem.parentNode;
	if (currentYearItem != yearItem){
		yearItem.style.backgroundColor = "#fff000";
	}
		tipText = yearItem.id.split(':')[0].split('Y')[1] + " (" + yearItem.id.split(':')[1] + ")";
		showYearCount(yearItem, tipText);
				
}

function zoomGraph(graphObj){
	var bigbarsize = 0;
	var paddsize = 0;
	for (graphItemsIndex=0; graphItemsIndex<jmjYearItems.length; graphItemsIndex++){
		jmjYearItems[graphItemsIndex].style.height = parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*4 + "px";
		jmjYearItems[graphItemsIndex].style.marginTop = (30 - parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*4) + "px";
		bigbarsize = (bigbarsize<(parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*4))?(parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*4 ):bigbarsize;
	}
	if (bigbarsize > 29){
		paddsize = bigbarsize-29;
	}else{
		paddsize=1;
	}
	document.getElementById("yearfiltershim").style.visibility = 'visible';
}

function zoomOutGraph(graphObj){
	for (graphItemsIndex=0; graphItemsIndex<jmjYearItems.length; graphItemsIndex++){
		jmjYearItems[graphItemsIndex].style.height = parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*2 + "px";
		jmjYearItems[graphItemsIndex].style.marginTop = (30 - parseInt(jmjYearItems[graphItemsIndex].id.split(":")[1])*2) + "px";
	}
	document.getElementById("yearfiltershim").style.visibility = 'hidden';
}

function hidexaxis(){
	document.getElementById('xaxis').style.display = 'none';
}
function lowlightYear(e){
	var yearItem;
	if (!e) var e = window.event;
	if (e.target) yearItem = e.target;
	else if (e.srcElement) yearItem = e.srcElement;
	if (yearItem.nodeType == 3) yearItem = yearItem.parentNode;
	if (currentYearItem != yearItem){
		yearItem.style.backgroundColor = "#039";
		hideTip();
	}
}
function showYearCount(jmjSrcObj, jmjTipTxt){
	jmjtipobj = document.getElementById('toolbartips');
	jmjtipobj.innerHTML=jmjTipTxt;
	jmjtipobj.style.display = 'block';
	jmjtipobj.style.left = (getPosition(jmjSrcObj)[0] - 30) + 'px';
	jmjtipobj.style.top = (getPosition(jmjSrcObj)[1] - 30) + 'px';
	jmjtipobj.style.zIndex = 999;
}

function getPosition(posObj){
	 var posX = posObj.offsetLeft;
	 var posY = posObj.offsetTop;
	 while(posObj.offsetParent){
	 posX=posX+posObj.offsetParent.offsetLeft;
	 posY=posY+posObj.offsetParent.offsetTop;
	 if(posObj==document.getElementsByTagName('body')[0]){break}
	 else{posObj=posObj.offsetParent;}
	 }
	 return [posX, posY];
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
            if (obj.tagName == 'DIV'){
                curtop -= obj.scrollTop;
            }
        }
    }
    return [curleft,curtop];
}

var contextMenuObj ='';
var refviewmenu='';

function showContextMenuNew(contextObj){
    clearTimeout(refviewmenu);
    if (contextMenuObj) contextMenuObj.style.display = 'none';
    contextMenuObj = contextObj.parentNode.parentNode.nextSibling;
	if ($("#tempcontextMenudiv").length == 0) $("#main_fulltext_content").append("<div id='tempcontextMenudiv' class='contextMenu' onmouseout='hideContextMenuNew();' onmouseover='keepContextMenuNew();' style='display:none; position:absolute; z-index:9999999;'><p></p></div>");
	$("#tempcontextMenudiv").html($(contextMenuObj).html());
	document.getElementById('tempcontextMenudiv').style.top = findPos(contextObj)[1] + 'px';
	document.getElementById('tempcontextMenudiv').style.left = findPos(contextObj)[0] + 10 + 'px';
	document.getElementById('tempcontextMenudiv').style.display = 'block';
}

function hideContextMenuNew(){
    if (contextMenuObj){ 
        refviewmenu = setTimeout("document.getElementById('tempcontextMenudiv').style.display = 'none';", 500);
    }
}

function keepContextMenuNew(){
    clearTimeout(refviewmenu);
    if (document.getElementById('tempcontextMenudiv')) document.getElementById('tempcontextMenudiv').style.display = 'block';
}

function resizeLargeFigure(largeFigureObj) {
	if (largeFigureObj)
	{
		if (largeFigureObj.width > 600){
			largeFigureObj.width = 600;
			}
	}
}

function setSelectedActivator(activatorObj, activatorClass){
    allActivators = document.getElementById("panelActivators").getElementsByTagName("LI");
    for (activateobjitem=0; activateobjitem<allActivators.length; activateobjitem++){
        allActivators[activateobjitem].className = '';
        }
    activatorObj.className = activatorClass;
}

function linkToMainTab(tabName) {
	$.historyLoad(tabName);
	document.getElementById("main_fulltext_content").scrollIntoView(true);
}

function setSwitchingofHighlightedSubtab(subTabObj) {
	$(".tabContent ul.backtabs li").removeClass("active"); 
		$(subTabObj).addClass("active"); 
		$('.intro-reftoggle').hide();
		var thisid = $(subTabObj).attr('id');
		$("#"+thisid+"-div").show();
}

var stodf;
function showinterviewcarrier(jmjaudiotoolobj){
	if (stodf) {clearTimeout(stodf);}
	document.getElementById("audiotool").className = 'audiotoolon';
    document.getElementById("authorinterviewcarrier").style.visibility='visible';
    document.getElementById("audioplayerholdertop").style.visibility='visible';
    audicarrpos = findPos(jmjaudiotoolobj);
    document.getElementById("authorinterviewcarrier").style.left = (audicarrpos[0]-10) + 'px';
    document.getElementById("authorinterviewcarrier").style.top = (audicarrpos[1]+20) + 'px';
}
function keepinterviewcarrier(){
	clearTimeout(stodf);
    document.getElementById("authorinterviewcarrier").style.visibility='visible';
    document.getElementById("audioplayerholdertop").style.visibility='visible';
}
function callhideinterviewcarrier(){
	stodf = setTimeout(hideinterviewcarrier, 1000);	
}
function hideinterviewcarrier(){
	document.getElementById("audiotool").className = (audioTopEmbeded)?'audiotoolon':'audiotool';
    document.getElementById("authorinterviewcarrier").style.visibility='hidden';
    document.getElementById("audioplayerholdertop").style.visibility='hidden';
}
function presentTopPlayer(){
    document.getElementById("audiotool").className="audiotoolon";
    showinterviewcarrier(document.getElementById("audiotool"));
    
    if (stodf) clearTimeout(stodf);
    stodf = setTimeout(hideinterviewcarrier, 3000);
}

function managesliders() {
	jmjAllPanels = sp1.getContentPanels();
	jmjPanelsLength = jmjAllPanels.length-1;
	for (panidx=jmjPanelsLength; panidx>=0; panidx--){
			var jmjcpitems = jmjAllPanels[panidx].getElementsByTagName('UL')[0].getElementsByTagName('li');
			var noofitems = jmjAllPanels[panidx].getElementsByTagName('UL')[0].getElementsByTagName('li').length;
			var jmjcpitemstotwidth=0;
			for (cpidx=0; cpidx<noofitems; cpidx++){
				var a = jmjcpitems[cpidx].offsetWidth * 1.1;
				jmjcpitemstotwidth = jmjcpitemstotwidth + a;
			}
			if (document.all) {
				jmjAllPanels[panidx].getElementsByTagName('UL')[0].style.width = jmjcpitemstotwidth + 'px';
			}else if (is_safari) {
				jmjAllPanels[panidx].getElementsByTagName('UL')[0].style.width = jmjcpitemstotwidth*(65/100);
			}else {
				jmjAllPanels[panidx].getElementsByTagName('UL')[0].style.width = jmjcpitemstotwidth + 'px';
			}
	}
}



function checkForAudioFlash(flashEnabledContentDiv, noFlashPlayerMessageDiv){
	if (document.all){
		 if (swfobject.hasFlashPlayerVersion("9")) {
			 if (document.getElementById(noFlashPlayerMessageDiv))
				{
				 	document.getElementById(noFlashPlayerMessageDiv).style.display='none';
				 	document.getElementById(flashEnabledContentDiv).style.display='block';
				}
		} else{
			if (document.getElementById(noFlashPlayerMessageDiv))
			{
		        document.getElementById(noFlashPlayerMessageDiv).style.display='block';
		        document.getElementById(flashEnabledContentDiv).style.display='none';
			}
		}
    } else {
		var MM_contentVersion = 6;
		var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;
		if ( plugin ) {
			var words = navigator.plugins["Shockwave Flash"].description.split(" ");
			for (var i = 0; i < words.length; ++i)
			{
			if (isNaN(parseInt(words[i])))
			continue;
			var MM_PluginVersion = words[i]; 
			}
			var MM_FlashCanPlay = MM_PluginVersion >= MM_contentVersion;
		}
		else if (navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 
		   && (navigator.appVersion.indexOf("Win") != -1)) {
			document.write('<SCR' + 'IPT LANGUAGE=VBScript\> \n'); //FS hide this from IE4.5 Mac by splitting the tag
			document.write('on error resume next \n');
			document.write('MM_FlashCanPlay = ( IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & MM_contentVersion)))\n');
			document.write('</SCR' + 'IPT\> \n');
		}
		if ( MM_FlashCanPlay ) {
			if (document.getElementById(noFlashPlayerMessageDiv))
			{
				document.getElementById(noFlashPlayerMessageDiv).style.display='none';
				document.getElementById(flashEnabledContentDiv).style.display='block';
			}
		} else{
			if (document.getElementById(noFlashPlayerMessageDiv))
			{
				document.getElementById(noFlashPlayerMessageDiv).style.display='block';
				document.getElementById(flashEnabledContentDiv).style.display='none';
			}
		}
	}
}
		

	String.prototype.clean = function(){
		var str= this.replace(/(^\s+)|(\s+$)/g,'');
		return str.replace(/ {2,}/g,' ');
	}

	var refrows = [];
		var refauthraw=[];
		var refauth=[];
		var refuauth=[];

function createAuthorFilter() {

	 $("#authorFilterImageDiv").mouseenter(
			function(){
				$(this).parent().css("z-indez","-1");
				$("#main_fulltext_content").append("<div id='tempauthfiltdiv' style='display:none; position:absolute; z-index:999; backgroundColor:red;'><p></p></div>");
				$("#tempauthfiltdiv").html($(this).html());				
				var tadobj = document.getElementById("tempauthfiltdiv");
				var tadsrcobj = document.getElementById("authorFilterImageDiv");
				tadobj.style.top = (findPos(tadsrcobj)[1]+2) + "px";
				tadobj.style.left = findPos(tadsrcobj)[0] + "px";
				if (document.all)
				{
					tadobj.style.left = (findPos(tadsrcobj)[0]-15) + "px";
				}
				tadsrcobj.parentNode.style.paddingLeft = "24px";
				tadobj.style.display = 'block';
				$(this).html('');
	 });

 	refrows = document.getElementById("refs_table").getElementsByTagName("TBODY")[0].getElementsByTagName("TR");

	for (i=0; i<refrows.length; i++){
			refauthraw.push(refrows[i].getElementsByTagName("TD")[0]);
	}
	
	for (j=0; j<refauthraw.length; j++){
		var tmpautharr = refauthraw[j].innerHTML.split('.,');
		for (k=0; k<tmpautharr.length; k++){
			var tempcleaner = tmpautharr[k].clean();
			var tempcleanest = tempcleaner.replace(/and/g, "");
			var temppurest = tempcleanest.clean();
			refauth.push(temppurest);
		}
	}
	var refsauth = refauth.sort();
	
	refuauth.push(refauth[0]);
	var uidx=0;
	for (l=1; l<refsauth.length; l++){
		refsauth[l] = (refsauth[l].charAt(refsauth[l].length-1) == '.')?(refsauth[l].substr(0,refsauth[l].length-1)):refsauth[l];
		refuauth[uidx] = (refuauth[uidx].charAt(refuauth[uidx].length-1) == '.')?(refuauth[uidx].substr(0,refuauth[uidx].length-1)):refuauth[uidx];
		if ((refsauth[l] != refuauth[uidx]) && (refsauth[l] != "et&nbsp;al") && (refsauth[l] != "")){
			uidx++;
			refuauth[uidx] = refsauth[l];
		}
	}
	for (m=0; m<refuauth.length; m++){
		for (n=0; n<refauthraw.length; n++){
			if (refauthraw[n].innerHTML.search(refuauth[m]) >-1){
				refauthraw[n].id = refauthraw[n].id + (refuauth[m].split(", ")[0]) + "~";
			}
		}
	}
	
	var refuauthmenu="<ul>";
	var floatindex=0;
	var floatcomputedindex = Math.round(refuauth.length/7);
	for (p=0; p<refuauth.length; p++){
		if (refuauth[p] != 'et al'){
			if (floatindex <= floatcomputedindex){
				refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + refuauth[p] + "</a></li>";
				floatindex++;
			}else{
				refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + refuauth[p] + "</a></li>";
				refuauthmenu = refuauthmenu + "</ul><ul>";
				floatindex=0;
			}
		}
	}
	document.getElementById("refauthfiltermenuitems").innerHTML = "<span>"+refuauthmenu + "</ul>" + "<span id='noauthormatched' style='display:none; clear:both;'><i style='color:black; font-weight:bold; font-size:13px;'>No authors found.</i></span><span style='display:block; clear:both;'></span></span>";
}		

var jmjauthmenuitems = [];

function showAuthorsNames(jmjfiltvalobj){
	if (jmjfiltvalobj.value!=''){
		var jmjauthmenuitems = [];
		for (p=0; p<refuauth.length; p++){
			if (refuauth[p] != 'et al'){
				if (refuauth[p].split(", ")[0].toLowerCase().indexOf(jmjfiltvalobj.value.toLowerCase()) == 0){
					jmjauthmenuitems.push(refuauth[p]);
				}
			}
		}
		var refuauthmenu="<ul>";
		var floatindex=0;
		var floatcomputedindex = Math.round(jmjauthmenuitems.length/7);
		for (p=0; p<jmjauthmenuitems.length; p++){		
				if (floatindex <= floatcomputedindex){
					refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + jmjauthmenuitems[p] + "</a></li>";
					floatindex++;
				}else{
					refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + jmjauthmenuitems[p] + "</a></li>";
					refuauthmenu = refuauthmenu + "</ul><ul>";
					floatindex=0;
				}
		}
		document.getElementById("refauthfiltermenuitems").innerHTML = "<span>"+refuauthmenu + "</ul>" + "<span id='noauthormatched' style='display:none; clear:both;'><i style='color:black; font-weight:bold; font-size:13px;'>No authors found.</i></span><span style='display:block; clear:both;'></span></span>";
		document.getElementById('noauthormatched').style.display = (jmjauthmenuitems.length > 0)?'none':'block';
	}else{
		var jmjauthmenuitems = [];
		document.getElementById('noauthormatched').style.display = 'none';
		var refuauthmenu="<ul>";
		var floatindex=0;
		var floatcomputedindex = Math.round(refuauth.length/7);
		for (p=0; p<refuauth.length; p++){		
				if (floatindex <= floatcomputedindex){
					refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + refuauth[p] + "</a></li>";
					floatindex++;
				}else{
					refuauthmenu = refuauthmenu + "<li><a href='javascript:void(0);' onclick='filterbyauthor(this.innerHTML);'>" + refuauth[p] + "</a></li>";
					refuauthmenu = refuauthmenu + "</ul><ul>";
					floatindex=0;
				}
		}
		document.getElementById("refauthfiltermenuitems").innerHTML = "<span>"+refuauthmenu + "</ul>" + "<span id='noauthormatched' style='display:none; clear:both;'><i style='color:red; font-weight:bold; font-size:14px;'>No Authors Found...</i></span><span style='display:block; clear:both;'></span></span>";
	}
}

function showAuthorFilterMenu(filterHeadobj){
	document.getElementById("refauthfiltermenu").style.top = (findPos(filterHeadobj)[1] - 10) + "px";
	document.getElementById("refauthfiltermenu").style.left = findPos(filterHeadobj.parentNode)[0] + "px";
	document.getElementById("refauthfiltermenu").style.display='block';
	document.getElementById("refauthfiltermenu").style.width='900px';
	document.getElementById("refauthfiltermenu").style.zIndex=999999;
	document.getElementById("refauthfiltermenuitems").style.zIndex=999999;
	if (document.all)
	{
		document.getElementById("refauthfiltermenu").style.top = (findPos(filterHeadobj)[1]) + "px";
		document.getElementById("refauthfiltermenu").style.left = (findPos(filterHeadobj.parentNode)[0] - 5) + "px";
	}
	if (is_nav)
	{
		document.getElementById("refauthfiltermenu").style.top = (findPos(filterHeadobj)[1] - 5) + "px";
		document.getElementById("refauthfiltermenu").style.left = (findPos(filterHeadobj.parentNode)[0] - 7) + "px";
	}
	return false;
}

function hideauthormenu(){
	document.getElementById("refauthfiltermenu").style.display='none';
}

function keepauthormenu(){
	document.getElementById("refauthfiltermenu").style.display='block';
}

function filterbyauthor(filtauthname){
	showAllYears();
	document.getElementById("refauthfiltermenu").style.display='none';
	showAllAuthors();
	for (n=0; n<refauthraw.length; n++){
		if (refauthraw[n].innerHTML.search(filtauthname) == -1){
			if (refauthraw[n].parentNode)
			{
				refauthraw[n].parentNode.style.display='none';
			}
		}
	}
	document.getElementById("trigAllAuth").style.display="block";
	document.getElementById("trigAllAuth").parentNode.style.width="300px";
	document.getElementById("authorFilterImageDiv").parentNode.style.paddingLeft = "48px";
}

function showAllAuthors(){
	for (n=0; n<refauthraw.length; n++){
			if (refauthraw[n].parentNode)
			{
				refauthraw[n].parentNode.style.display='';
			}
	}
	document.getElementById("trigAllAuth").style.display="none";
	document.getElementById("authorFilterImageDiv").parentNode.style.paddingLeft = "24px";
}

function findSearchTermInArticle(){
	searchterm = $('#findterm').val();
	if (searchterm) {
		$('#load').removeHighlight().highlight(searchterm);
		$("#ajaxanim").show();
		getAotfResearchArticleSearchResults(getArticlePII(), searchterm);
		$("#ajaxanim").hide();
	}
}

function sortAlphabetically(sourceString, targetString) {
	sourceString = sourceString.toLowerCase();
	targetString = targetString.toLowerCase();
	if (sourceString > targetString ) return 1;
	if (sourceString < targetString ) return -1;
	return 0; 
}

function setContentBoxHeight()
{
	if(document.getElementById('upsell') && document.getElementById('load')) {
	document.getElementById('upsell').style.display='block';
	document.getElementById('load').style.height='618px';
	document.getElementById('load').style.padding='26px 0';
   }
}

function jobAdsScript(advertUri){
	var ord = Math.random()*10000000000000000;
	document.write('<script type="text/javascript" src="https://ad.doubleclick.net/adj/' + advertUri +';pos=top;tile=2;sz=180x300;ord=' + ord + '?"><\/script>');		
}

function showClassifiedJobAds(advertUri) {
		var ord=Math.random()*10000000000000000;
		document.write('<script type="text/javascript" src="http://ad.doubleclick.net/adj/' + advertUri +';pos=bottom;sz=180x150,180x450;ord=' + ord + '?"><\/script>');
}

function populateCaption(){
	if ($("div#mockcaptionscroller").length > 0 && $("#mockcaptionscroller").html().length > 0)
	{
		$("#captionscroller").html($("#mockcaptionscroller").html());
	} else {
		$("#showcaption").hide();
	}
}

function setUpClickEventsForShowAndHideCaption() {
	$("#showcaption").click(function(e){
		$("#hidecaption").show();
		$("#showcaption").hide();
		getheight = $("#figuredetails").height()
		$("#zoomcaptionscrollDiv").height(getheight);
		$("#zoomcaptionscrollDiv").show();
		$("#veil_bottom").css("top",getheight + 1);
		$("#captionscroller").height(getheight - 2);
		e.preventDefault();
	});

	$("#hidecaption").bind('click', function(e){
		$("#showcaption").show();
		$("#hidecaption").hide();
		$("#zoomcaptionscrollDiv").hide();
		return false;
	});
}


function showTableAndHideCaption(){
	if($("#tablediv").length > 0 && $("#tablediv").html().length > 0) {
		$("#tablediv").width($("#figuredetails").width()-10);
		$("#tablediv").height($("#figuredetails").height()-54);
		$("#tablediv").show();
		$("#hideshowcaption").hide();
	}
	else {
		$("#hideshowcaption").show();
	}
}

function setUpFiguresClickEventsInResultsTabLHS(tabName) {
	$(".zoom").bind('click', function(e) {
		figclick = $(this).attr("ref");
		figclick = figclick.toString(); 
		figtab = "figtab-"+figclick;
		$("#figtabs li").removeClass("active"); 
		$("#"+figtab).addClass("active");
		refid=$(this).attr("ref");
		switchZoomFiguresInResultsTab(refid, getArticlePII(), tabName);
		set_figtab_range($(".Rpane").width()); 
		$("#hidecaption").trigger('click');
		e.preventDefault();
	});

	$("#figtabs li").bind('click', function(e) {
		var refid=$(this).attr("ref");
		$("#figtabs li").removeClass("active"); 
		$("#figtab-"+ refid).addClass("active"); 
		switchZoomFiguresInResultsTab(refid, getArticlePII(), tabName);
		$("#hidecaption").trigger('click');
		return false;
	});
}	

var figtab_last;
var figtab_range;
var figtab_size;
function set_figtab_range(figwidth){
	$("#nexttab").css("visibility","hidden");
	activetab=$("#figtabs li.active");
	activeindex = $("#figtabs li").index(activetab);
	figtab_range = Math.floor((figwidth - 160)/56);  
	figtab_size = $("#figtabs").children().size();
	if (activeindex > figtab_range) { 
		$("#figtabs li").each(function (i) {
			if (i > (activeindex - figtab_range) && (i < (activeindex + figtab_range - 1))) {
				$(this).css("display","inline");
				figtab_last = i;
			} else { 
				$(this).css("display","none");	
				if (i==0) { 
					$("#prevtab").css("visibility","visible");
				}
			}
			if (i == (activeindex + figtab_range - 1) && (i < (figtab_size - 1)))
				{
					$("#nexttab").css("visibility","visible");
			}
		});		
	} else {  //most often the tabs are at position 0
		$("#figtabs li").each(function (i) {
			if (i<=figtab_range) {
				$(this).css("display","inline");
				figtab_last = i;
			}else { 
				$(this).css("display","none");	
				$("#nexttab").css("visibility","visible");
			};
		});		
		$("#prevtab").css("visibility","hidden");
	};
	figtabnums();
}


function movefigtabs(dir) {  //prev or next
	activetab=$("#figtabs li.active");	
	(dir == "next") ? newactive = activetab.next() : newactive = activetab.prev(); 
	(dir == "next") ? figtab_last++ : figtab_last--;
	$("#figtabs li").each(function (i) {						
		$(this).css('display','none');
		if (i >= (figtab_last - figtab_range) && i <= figtab_last) {
			$(this).css('display','inline');
		}
	});
	newactive.addClass("active");
	newactive.trigger("click");	
	if (figtab_last==(figtab_size-1)) { 
		$("#nexttab").css("visibility","hidden");
	} else{
		$("#nexttab").css("visibility","visible");
	};
	if (figtab_last > figtab_range) { 
		$("#prevtab").css("visibility","visible");
	} else{
		$("#prevtab").css("visibility","hidden");
	};
	figtabnums();
	return false;
}

function figtabnums() {
		nextnumval = figtab_size-(figtab_last+1);
		$("#nextnum").html("("+nextnumval+")");
		$("#nexttab").attr("title", nextnumval + " more tabs");
		prevnumval= Math.abs(figtab_range-figtab_last)
		$("#prevnum").html("("+prevnumval+")");
		$("#prevtab").attr("title",prevnumval + " more tabs");
}

function setMainTextpanels(){	
	$("#outlinelist").height($(".Lpane").height()-32);
	$("#figuredetails").height($(".Rpane").height()-36); // JJ 6/20/2011
	figdetail_h = $(".Rpane").height()-46;
	$("#figuredetails").css("height",figdetail_h);
	$("#zoomfigure").height($(".Rpane").height()-120);  //was 42 $("#zoomfigure").height($("#figuredetails").height()-42)
}

function setClickEventsOnFilmStripsTabs() {
	$("#filmstriptabs ul li a").click(function(){
			thisid = $(this).attr('id');
			$('.figdetail_imageHolder').show();
			$("#filmstriptabs ul li").removeClass("active"); 
			$(this).parent().addClass("active"); 
			$('.filmstrip').hide();
			filmstripid = "filmstrip_" + thisid;
			$('#'+filmstripid).show();
			return false;
		});
}

function setAOTFADheight() { 
	browserheight = window.innerHeight;
	browserwidth = window.innerWidth;
	if(browserwidth == undefined)
		browserwidth = $(window).width();
	$(".ajaxcontainer, #aotfheader").width(browserwidth-230); 
	$(".ajaxcontainer, #aotfheader").css("min-width","786px");
};


function getArticlePII(){
 	return $('#articlePII').val();
}

function setPageAnchoring() {
	var hash = $("ul.backtabs li.active a").attr("href");
	hash = hash.replace(/#/i, "");	
	cellheaderheight = ($("#aotfheader").height() + 196);
	firsttab = $("a[rel='history']").attr("href");
	firsttab_hashname = firsttab.replace(/#/i, "");	
	if ((hash == "")||(hash == firsttab_hashname)) {	
	} 
	else{
		$(window).scrollTop(cellheaderheight);
	}
}
