/* This file contains commonly used functions. */
var VISIBLE='visible';
var HIDDEN='hidden';
var ns = true;
var mac = true;
var is_safari = (navigator.userAgent.toLowerCase().indexOf('safari') != -1);
var netscape7 = (navigator.userAgent.toLowerCase().indexOf('netscape/7.0') != -1);
var opera = (navigator.userAgent.toLowerCase().indexOf('opera') != -1);
var sessID = 'hwwilsonid';

function checkPageStatus( )
{
	if (!searchRunning)
	{
		searchRunning = true;
		status = 'Processing.....';
		return true;
	}
	else
	{
		return false;
	}
}

function setSessID (newID)
{
	sessID = newID;
}

// Encode an URL with sessionID.
// If allURL is true, it encodes all url's
// If skipReplaceDot is false, it replaces .. with hww
// Default usage on hidden.jhtml (url,sessionID,false,false);

function _EncodeWithSessionID(url,sessionID,allURL,skipReplaceDot)
{
	// Only encode jhtml's, not html's
	if (allURL || url.lastIndexOf('jhtml') > 0)
	{
		if (url.lastIndexOf('?') < 0)
		{
			url += ";"+sessID+"=" + sessionID;
		}
		else
		{
			url = url.replace(/\?/, ";"+sessID+"=" + sessionID + "?");
		}
		//AGC 6.16.03 added to test login prob for mass libraries - see 6290
		//alert(url);
		if (!skipReplaceDot)
		{
			url = url.replace(/\.\.\//, "\/hww\/");
		}
		//alert(url);
		//Mitsu 09/17/04
		url = url.replace(/&amp;/g, "&");
	}
	return url;
}

function do_externalLink( href )
{
	//if (checkPageStatus())
	//{
		//top.maincontentframe.mainframe.clearSelected(  );
		//top.hidden.bottomToolbar = "back_toolbar";
		//top.bottomframe.showToolbar();
		//toggleDiv (top.bottomframe.document, 'goBack', HIDDEN, true);
		//top.hidden.result_type="hyperlink";
		//top.hidden.search_done = true;
		//var srchVals=getCookieValues(SRCH_COOKIE);
		//srchVals[S_DONE]=true;
		//setCookieValues(SRCH_COOKIE,srchVals,'/');
		//parent.mainframe.document.externalLinkForm.ExternalURL.value = href;
		//parent.mainframe.document.externalLinkForm.submit( );
		//top.maincontentframe.mainframe.document.externalLinkForm.ExternalURL.value = href;
		//top.maincontentframe.mainframe.document.externalLinkForm.submit( );
		//document.externalLinkForm.ExternalURL.value = href;
		//document.externalLinkForm.submit( );
		openWindow (href);
	//}
}

//This file contains functions from results_common.jhtml, results_single.jhtml
function WriteHTML(str,allID,layID,elmID)
{
	if (document.all)
	{
		var qString = document.all[allID];
		if (qString) qString.innerHTML = str;
	}
	else
	{
		// Netscape
		if (document.getElementById)
		{
			// Netscape 6
			var query = document.getElementById(allID);
			if (query) query.innerHTML = str;
		}
		else
		{
			// older Netscape
			if (document.layers[layID].document)
			{
				document.layers[layID].document.open("text/html");
				document.layers[layID].document.write('<span class="an">'+str+'</span>');
				document.layers[layID].document.close();
			}
		}
	}
}

function trim(s)
{
	if (s == null)
	{
		return s;
	}
	// Remove leading spaces and carriage returns
	while ((s.substring(0,1) == ' ')
		|| (s.substring(0,1) == '\n')
		|| (s.substring(0,1) == '\r'))
	{
		s = s.substring(1,s.length);
	}
	// Remove trailing spaces and carriage returns
	while ((s.substring(s.length-1,s.length) == ' ')
		|| (s.substring(s.length-1,s.length) == '\n')
		|| (s.substring(s.length-1,s.length) == '\r'))
	{
		s = s.substring(0,s.length-1);
	}
	return s;
}

//moved from activesearches.jhtml. Brinda 03/13/09.
function IsNumeric(sText)
{
 var ValidChars = "0123456789";
 var IsNumber=false;
 var Char;
 for (i = 0; i < sText.length; i++)
 {
		Char = sText.charAt(i);
		if (ValidChars.indexOf(Char) != -1)
		{
			 IsNumber = true;
		}
	}
 return IsNumber;
}

function checkFld(whichObj)
{
	if (IsNumeric(whichObj.value))
	{
		goToPage(whichObj.value);
	}
	else
	{
		alert("Please enter valid page number");
		whichObj.focus();
	}

}

//Added to log after the last byte has been sent to user. Wing 9/20/2004
function logLast (actionVal)
{
	$.ajax({
		url: '/hww/shared/logLast.jhtml',
		cache: false,
		data: {action:actionVal}
		//complete: function (XMLHttpRequest, textStatus) { alert (textStatus); }
	});
}
/*moved to search.jhtml to get language specific values..
function updateSelectedDBs (expandNode)
{
	if (searchRunning) return;
	if (expandNode)
	{
		CTrees['dbFormTree'].expandNode(0);
	}
	if (dbTree.nodeByID (0).expanded)
	{
		//WriteHTML ('<table width="75%"><tr><td align="right"></td></tr></table>', 'selectedDBs', 'i1', 'selDBs');
		WriteHTML ('', 'selectedDBs', 'i1', 'selDBs');
		WriteHTML ('<a href="javascript:updateSelectedDBs(true);"><img src="../images/minus.gif" border="0" style="vertical-align:bottom;"/></a><a class="csLinks" title="Click to collapse the Database Selection area" href="javascript:updateSelectedDBs(true);">Close Database Selection Area</a>', 'prompt', 'i2', 'promptStr');
		WriteHTML ('', 'DBdesc', 'i3', 'DBdescstr');
		WriteHTML ('','jnDir', 'i4', 'jnDirLinkstr');
	}
	else
	{
		if (productNames == null || productNames.length == 0)
		{
			productNames = '';
		}
		WriteHTML (productNames, 'selectedDBs', 'i1', 'selDBs');
		WriteHTML ('<a href="javascript:updateSelectedDBs(true);"><img src="../images/plus.gif" border="0" style="vertical-align:bottom;"/></a><a class="csLinks" title="Click to expand the Database Selection area" href="javascript:updateSelectedDBs(true);">Open Database Selection Area</a>', 'prompt', 'i2', 'promptStr');
		WriteHTML ('<img src="../images/littlebluebutton.gif" border="0"><a href="javascript:openDBDescs()" class="csLinks">Database Descriptions</a>','DBdesc', 'i3', 'DBdescstr');
		WriteHTML ('<img src="../images/littlebluebutton.gif" border="0"><a href="javascript:openWinJDir()" class="csLinks">Journal Directory</a>', 'jnDir', 'i4', 'jnDirLinkstr');
	}
	if ( !dbTree.nodeByID(0).expanded )
	{
		if (!is_safari && !netscape7)
		{
			if (location.hash != '#formTop')
			{
				location.hash = 'formTop';
			}
		}
		setQFocus ();
	}
}*/

function setQFocus ()
{
	if (PlayState == VISIBLE)
		document.playForm.tipl.focus ();
	else
	{
		try
		{
			var f = document.queryform;
			if (BioState == VISIBLE && f.firstName)
			{ f.firstName.focus(); }
			else if ( f.query )
			{ f.query.focus(); }
			else if ( f.query1 )
			{ f.query1.focus(); }
		}
		catch (e) { }
	}
}

function toClipboard( theHref, btxt )
{
	if (btxt)
	{
		theHref = theHref + '\r\n' + unescape(btxt);
	}
	// If IE
	if ( window.clipboardData )
	{
		window.clipboardData.clearData();
		window.clipboardData.setData("Text", theHref);
		alert ('URL copied to clipboard: ' + theHref);
	}
	// If Netscape
	else
	{
		// Look for the form element with the desired name
		prompt("Link to Search : Use ctrl-c to copy the link below to your clipboard.  Use ctrl-v to paste the link into your e-mail or document.\n\n", theHref);
	}
	return false;
}

// AGC 12/16/04 open window function that sets back page
/* open first window */
function openWindow(URL, winName, winW, winH)
{
	if (!winName) winName = 'win1';
  //oWindow= open( URL , targetName);
	//oWindow.focus();
	openWinNow (null, winName, URL, null, winW, winH);
}

/* open an empty window, if (form != null) submit the form (the form must
   have win1 as target*/
function openWinNow (theForm, winName, URL, extraParams, winW, winH, winFeatures)
{
	if (!winW || winW <= 0) winW = 475;
	if (!winH || winH <= 0) winH = 400;
	var topX = (window.screen.width/2)-(winW/2);
	if (!winFeatures) winFeatures = "toolbar=yes,location=no,directories=no,buttons=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,";
	var u = (theForm) ? "" : EncodeWithSessionID ('/hww/shared/wait.jhtml?p=' +
		(extraParams ? extraParams : "") + '&u=' + (URL ? escape (URL) : ""));

	/*windowVar = window.open (u, winName,
			"toolbar=yes,location=no,directories=no,buttons=yes," +
			"status=yes,menubar=yes,scrollbars=yes," +
			"resizable=yes,width=" + winW + ",height=" + winH);*/

	windowVar = window.open (u, winName,winFeatures+"width="+winW+",height="+winH+",left="+topX+",top=0");
	if (theForm)
		theForm.submit ();
	//else if (windowVar && !extraParams)
	//	windowVar.location = URL;
	//setTimeout ("windowFocus();", timeElapsed);
}

/* open second window */
function openWin (URL)
{
	openWinNow (null, 'win2', URL);
}

var timeElapsed=1500; // 1.5 seconds
var windowVar = null;
var VALID_EXT={};
var a = '.jpg,.jpeg,.png,.gif,.bmp'.split(',');
for (var p in a)
{
	VALID_EXT[a[p]]=1;
}

function waitAndCheck(url,windowName,windowFeatures)
{
	if (url == null)
		url = '';
	var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	var urlType = url.toLowerCase().match(urlString);
	if (VALID_EXT[urlType])
	{
		var imgLnk = '/hww/shared/imgView.jhtml?url=' + escape(url);
		windowVar = window.open (imgLnk,windowName,windowFeatures);
	}
	else
	{
		windowVar = window.open(url,windowName,windowFeatures);
	}
	/*
	if (url !=null && windowName==null && windowFeatures==null)
	{
		windowVar = window.open(url)
	}
	else if (windowFeatures==null && windowName !=null && url!=null)
	{
		windowVar = window.open(url,windowName)
	}
	else if (windowFeatures!=null && windowName !=null && url!=null)
	{
		windowVar = window.open(url,windowName,windowFeatures);
	}*/
	//setTimeout ("windowFocus();", timeElapsed);
}

function _waitAndCheck(url,windowName,windowFeatures)
{
	if (url == null)
		url = '';

	if (url !=null && windowName==null && windowFeatures==null)
	{
		windowVar = window.open(url)
	}
	else if (windowFeatures==null && windowName !=null && url!=null)
	{
		windowVar = window.open(url,windowName)
	}
	else if (windowFeatures!=null && windowName !=null && url!=null)
	{
		windowVar = window.open(url,windowName,windowFeatures);
	}
	//setTimeout ("windowFocus();", timeElapsed);
	return windowVar;//AGAG need handle to close window
}

function windowFocus ()
{
	if (windowVar == null || windowVar.closed)
	{
		alert ("We are unable to complete this function because your browser's popup window blocker is active/enabled.  Please either disable your popup blocker, or include WilsonWeb among your popup blocker's approved sites.  The following WilsonWeb address should be added to your list of approved sites:  http://vnweb.hwwilsonweb.com.  You may also want to add Wilson's Home page to your list of approved sites: http://www.hwwilson.com.   Thank you.");
	}
	else
	{
		windowVar.focus();
	}
}

var ie4 = (document.all) ? true : false;
var ns4 = (document.layers) ? true : false;
var ns6 = (document.getElementById && !document.all) ? true : false;

function toggleDiv(doc, objID, vStyle, tableID, cName)
{
	var dStyle =(vStyle == HIDDEN ? 'none' : (tableID && !ie4) ? '' : (opera ? 'table-row' : 'inline'));

	if(ns6 && doc.getElementById(objID) != null)
	{
		doc.getElementById(objID).style.visibility=vStyle;
		doc.getElementById(objID).style.display=dStyle;
		if (cName) doc.getElementById(objID).className=cName;
	}
	else if(ns4 && doc.layers[objID] != null)
	{
		doc.layers[objID].visibility = vStyle;
		doc.layers[objID].display=dStyle;
		if (cName) doc.layers[objID].className=cName;
	}
	else if(ie4 && doc.all[objID] != null)
	{
		doc.all[objID].style.visibility = vStyle;
		doc.all[objID].style.display=dStyle;
		if (cName) doc.all[objID].style.className=cName;
	}
}

function toggleFontWeight (doc, objID, fWeight)
{
	if (ns6 && doc.getElementById(objID) != null)
	{
		doc.getElementById(objID).style.fontWeight=fWeight;
	}
	else if (ns4 && doc.layers[objID] != null)
	{
		doc.layers[objID].fontWeight = fWeight;
	}
	else if (ie4 && doc.all[objID] != null)
	{
		doc.all[objID].style.fontWeight = fWeight;
	}
}

function openDBDescs ()
{
	if (products_selected != "")
	{
		openWindow ("/hww/help/popup/popup_databaseHelp_main.jhtml?prods=" + products_selected,'win1',660,400);
	}
	else
	{
		alert ("Please select at least one database");
	}
}

function toggleBack(targetDoc, visibility)
{
	toggleDiv (targetDoc, "searchBack", visibility ? VISIBLE : HIDDEN);
	toggleDiv (targetDoc, "searchNoBack", visibility ? HIDDEN : VISIBLE);
}

function checkURL (url)
{
	if (url && (url.substring(0,7) == "http://" || url.substring(0,8) == "https://"))
		return true;
	return false;
}

function skip () { this.blur(); }

function toggleSel (selElm, enabled)
{
	selElm.disabled = !enabled;
	if (!document.all && !document.getElementById)
	{
		if (!enabled)
		{
			selElm.oldOnFocus = selElm.onfocus ? selElm.onfocus : null;
			selElm.onfocus = skip;
		}
		else
		{ select.onfocus = select.oldOnFocus; }
	}
}

function selectBottom() {}

function checkKey(field, evt)
{
	var key;
	if (document.all)
	{
		key = evt.keyCode;
	}
	else if (document.getElementById)
	{
		if (evt)
		{	key = evt.keyCode; }
	}
	else
	{ key = evt.which; }

	if (key == 13)
	{
		return true;
	}
	return false;
}

function getSelectedProds ()
{
	var resVals=getCookieValues(RES_COOKIE);
	return resVals[RES_SEL_PRODS];
}

function setSelectedProds (prods)
{
	var resVals=getCookieValues(RES_COOKIE);
	resVals[RES_SEL_PRODS]=prods;
	setCookieValues(RES_COOKIE,resVals,'/');
}

function toggleThesTab (prods_selected)
{
	var showTTab = showThesTab (prods_selected);
	var v = showTTab ? VISIBLE : HIDDEN;
	var a = 'thes,thes1,thes_s_1,thes_s_2'.split(',');
	for (var id in a)
		toggleDiv (document, a[id], v, 1);
	if (!showTTab && "Thesaurus" == curLink)
		Go(ADV_SRCH);
}

function getshSectionName()
{
	var shVals = getCookieValues(SIGNIN_COOKIE);
	return shVals[SH_SECT_NM];
}

function setshSectionName(section)
{
	var shVals = getCookieValues(SIGNIN_COOKIE);
	shVals[SH_SECT_NM] = section;
	setCookieValues (SIGNIN_COOKIE,shVals,'/');
}

function setActiveTab(e,idx)
{
	var shVals = getCookieValues(SH_COOKIE);
	if(idx)
		shVals[SH_TAB] = idx;
	else
		shVals[SH_TAB] = tabView.get('activeIndex');
	setCookieValues (SH_COOKIE,shVals,'/');
}

function switchLang (newLangCode)
{
	if(curLink == 'RefsSubTopicsResults')
	{
		with(document.hiddenSettings)
    	{
    			K2Query.value='refsLast';
				startRow.value='1';
				endRow.value='1';
				displayType.value='full';
				actionType.value="doCurrent";
				langCode.value = newLangCode;
				submit();
		}
	}
	else
	{
		document.newLang.langCode.value = newLangCode;
		document.newLang.langChanged.value=1;
		document.newLang.submit();
	}
}
function do_Signin()
{
	//setActiveTab(null,1);
	Go('MyWWeb');
}

function do_Signout()
{
	var shVals = getCookieValues(SH_COOKIE);
	shVals[SH_SEL]="";
	shVals[SH_DEL]="";
	shVals[SH_NUM_SEL]=0;
	setCookieValues (SH_COOKIE,shVals,'/');
	document.idForm.id.value="";
	document.idForm.userName.value="";
	document.idForm.status.value='signOut';
	document.idForm.submit();
}

function hlTab (tabName)
{
	$('#' + tabName + 'Tab').removeClass ().addClass ('activeLimitTab');
	$('#' + tabName + '_ir').removeClass ().addClass ('activeLimitRight');
	$('#' + tabName).removeClass ().addClass ('activeLimitLink');
	if (tabsSelected) tabsSelected[tabName]=1;
	if (titleLabels && titleLabels[tabName][TITLE_POS])
	{
		$('#' + tabName).attr ("title", titleLabels[tabName][TITLE_POS]);
	}
	/*
	if(document.getElementById(tabName + 'Tab'))
		document.getElementById(tabName + 'Tab').className = 'activeLimitTab';
	if(document.getElementById(tabName + '_ir'))
		document.getElementById(tabName + '_ir').className = 'activeLimitRight';
	if(document.getElementById(tabName))
		document.getElementById(tabName).className = 'activeLimitLink';*/
}

function changeTab (tabName, inactive)
{
	if (!inactive) inactive = '';
	$('#' + tabName + 'Tab').removeClass ().addClass (inactive + 'activeTab');
	$('#' + tabName + 'Right').removeClass ().addClass (inactive + 'activeRight');
	$('#' + tabName + 'Link').removeClass ().addClass (inactive + 'activeLink');
	/*
	document.getElementById(tabName + "Tab").className = inactive + 'activeTab';
	document.getElementById(tabName + "Right").className = inactive + 'activeRight';
	document.getElementById(tabName + "Link").className = inactive + 'activeLink';*/
}

var _maxWidth=105;
var _maxHeight=70;
function resizeImg (imgObj)
{
	var w,h;
	if ((w = imgObj.width) && (h = imgObj.height))
	{
		if (w == h && w > _maxHeight)
		{ //sqaure
			w = h = _maxHeight;
		}
		else if (w > h)
		{ //#portrait
			if (h > _maxHeight)
			{
				w = Math.floor(w * (_maxHeight / h));
				h = _maxHeight;
			}
			if (w > _maxWidth)
			{
				h = Math.floor (h * (_maxWidth / w))
				w = _maxWidth;
			}
		}
		else//landscape
		{
			if (w > _maxWidth)
			{
				h = Math.floor (h * (_maxWidth / w));
				w = _maxWidth;
			}
			if (h > _maxHeight)
			{
				w = Math.floor (w * (_maxHeight / h));
				h = _maxHeight;
			}
		}
		imgObj.width = w; imgObj.height = h;
		imgObj.style.visibility='visible';
	}
	else
	{
		setTimeout (function() { resizeImg (imgObj); } ,500);
	}
}

function slideShow (imgUrl,curImg,query)
{
	//tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	if (!query) query = 'td a';
	tb_showAjax(imgUrl, curImg, query);
}

/*function slideShow(objID)
{
	$('a[@rel*=lightbox]').lightBox(); 
}*/

/* For read speaker YSHAH 11/07/2008 */
var voices=new Array();
voices[0]='Paul';
voices[1]='Kate';
function readspeaker(rs_call, rs_file_name, vPos)
{
	var df = document.displayform;
	if (df && df.curIdx && df.curIdx.value)
	{
		rs_call += escape ("&PARAMS=Which|" + df.curIdx.value);
	}
	rs_call+= "&voice=" + voices[vPos];
	savelink=rs_call+"&save=1&audiofilename="+rs_file_name;
	rs_call=rs_call+"&output=audio";
	rs_call=escape(rs_call);
	//prompt ('rs_call', unescape(unescape (rs_call)));
	start_rs_table="<table style='border:1px solid #aeaeae; font-size: 10px;'><tr><td>";
	rs_embed="<object type='application/x-shockwave-flash' data='/hww/readspeaker19.swf?mp3="+rs_call+"&autoplay=1&rskin=bump' height='20' width='250'><param name='movie' value='/hww/readspeaker19.swf?mp3="+rs_call+"&autoplay=1&rskin=bump'><param name='quality' value='high'><param name='SCALE' value='exactfit'><param name='wmode' value='transparent'><embed wmode='transparent' src='/hww/readspeaker19.swf?mp3="+rs_call+"&autoplay=1&rskin=bump' quality='high' pluginspage='http://www.macromedia.com/go/getflashplayer' type='application/x-shockwaveflash' scale='exactfit' height='20' width='250'></embed></object>";
	rs_downloadlink="<br>Speech-enabled by <a href='http://www.readspeaker.com'>ReadSpeaker</a><br><a href='"+savelink+"'>Download audio</a>";
	close_rs="<br /><a href='#' onclick='close_rs_div(\"" + vPos + "\"); return false;'>Close window</a>";
	end_rs_table="</td></tr></table>";
	var x=document.getElementById('rs_div'+vPos);
	x.innerHTML=start_rs_table+rs_embed+rs_downloadlink+close_rs+end_rs_table;
	for (var p=voices.length - 1; p >= 0; p--)
	{
		if (p != vPos)
		{
			close_rs_div (p);
		}
	}
}

function close_rs_div(vPos)
{
	var x=document.getElementById('rs_div' + vPos);
	x.innerHTML="";
}

var titleLabels={};
var TITLE_POS=0;
var QUERY_POS=1;
var RXQUERY_POS=2;
var ENG_Q_POS=3;
var A_ENG_POS=4;

titleLabels['ftpdf']=['Remove Full Text PDF','p <in> fti',/\s*p\s*<in>\s*fti\s*,?/ig,'PDF','PAGE_IMAGE'];
titleLabels['pr']= ['Remove Peer Reviewed','y <in> pri',/\s*y\s*<in>\s*pri\s*/ig,'Peer Reviewed','PEER_REVIEWED'];
titleLabels['pop']=['Remove Non-Peer Reviewed','<and> (<not> (y <in> pri))',/\s*<and>\s*(\s*<not>\s*(\s*y\s*<in>\s*pri\s*)\s*)\s*/ig,'Non-Peer Reviewed','NON-PEER_REVIEWED'];
titleLabels['fthtml']=['Remove Full Text','y <in> fti',/\s*y\s*<in>\s*fti\s*/ig,'Full Text','FULL_TEXT'];
titleLabels['bios']=['Remove Bios/Obits','y <in> (obi,bioi)',/\s*y\s*<in>\s*(\s*obi\s*,\s*bioi\s*)\s*/ig,'Bios/Obits','BIO_OBIT'];
titleLabels['img']=['Remove Image','y <in> pii',/\s*y\s*<in>\s*pii\s*/ig,'Image','IMAGES'];
titleLabels['fmi']=['Remove Film Records','y <in> fmi',/\s*y\s*<in>\s*fmi\s*/ig,'Film Records','Film Records'];

function unescapeEnt (str)
{
	if (str)
		str = unescape (str).replace (/&lt;/g,"<").replace (/&gt;/g,">").replace(/&quot;/g,'"');
	return str;
}

function updateCDF (cdfValue)
{
	var forms = document.forms;
	for (var f = forms.length - 1; f >= 0; f--)
	{
		if (forms[f].citationDisplayFields)
		{
			forms[f].citationDisplayFields.value = cdfValue;
		}
	}
}

function toTarget(targetName)
{
	var $target = $('a[name=' + targetName + ']');
	if ($target.length) {
		var targetOffset = $target.offset().top;
		$('html,body').animate({scrollTop: targetOffset}, 'fast');
	}
}