var mapExpanded = false;
var strURL = document.location + '';

function init() {
  //*** The Scopus API requires different Developer IDs for different URLs.
  //*** When pushing this code LIVE I'd recommend removing the unnecessary lines.
  if (strURL.indexOf('://info.scopus.com/topcited') > 0) {
    //*** http://info.scopus.com/topcited
    scapi.setDeveloperID("AirWL0BE8beTubUF6654WrWioeSGTj");
  } else if (strURL.indexOf('://www.info.scopus.com/topcited') > 0) {
    //*** http://www.info.scopus.com/topcited
    scapi.setDeveloperID("c8OEFDcnD5rSxuO75nKUeq3FEa9RQI");
  } else if (strURL.indexOf('://staging.info.scopus.com/topcited') > 0) {
    //*** http://staging.info.scopus.com/topcited
    scapi.setDeveloperID("b82ykaCDK8hYk1vLPXrhVJ10jFAI8c");
  } else if (strURL.indexOf('topcited.com') > 0) {
    //*** www.topcited.com
    scapi.setDeveloperID("KLrM4uoCkTECwnMeGhhd88VP4UJCcK");
  } else {
    //*** localhost
    scapi.setDeveloperID("fWehv0sCXYdMzWdPknvutY9vIAufxi");
  }
  
  scapi.setCallback(callback);
  scapi.setErrorCallback(callbackError);

  fixBackground();
  setMapPosition();
  loadGMap();
  runSearch();
  window.setInterval(setMapPosition, 1000);
}

function runSearch() {
  var varSearchObj = new searchObj();
  var strSearchString = '';
  var blnDoSearch = true;

  if (document.frmSearch.selSubjectArea.value != '') {
    strSearchString += 'SUBJAREA(' + document.frmSearch.selSubjectArea.value + ') AND ';
  }
  if (intFromYear() != -1) {
    strSearchString += 'PUBYEAR AFT ' + intFromYear();
  }


  if (blnDoSearch) {
     displaySearchQuery();

     varSearchObj.setSearch(strSearchString);
     varSearchObj.setSort('CitedByCount');

	varSearchObj.setFields('title,doctype,citedbycount,inwardurl,sourcetitle,issn,vol,issue,page,pubdate,eid,scp,doi,firstauth,affiliations');

	//varSearchObj.setFields('title,doctype,citedbycount,inwardurl,sourcetitle,issn,vol,issue,page,pubdate,eid,scp,doi,firstauth,affiliations,abstract');
      varSearchObj.setNumResults(intNumArticles);
     document.getElementById('divResults').innerHTML = '<img src="images/logo_spin_12.gif" width="34" height="28" alt="Searching ..." title="Searching ..." border="0" align="absmiddle" vspace="10" hspace="10">&nbsp;<span id="spnSearching">Searching ... </span>';
     scapi.search(varSearchObj);
     //*** The standard SCAPI output is rendered in the invisible layer "divResults". If it's possible to skip this step, then please feel free to do so, as it takes extra time and resources.
     //*** The real rendering happens in the callback() function!
   }
   getRssUrl(strSearchString);
}

function callback() {
  var strResultsHtml = '';
  var intResult = 0;

  //gmap
  var text = '';
  var firstResult = true;
  var retryCount = 0;
  var a = 0;

InitSerializer ();
map.clearOverlays();
  if (scapi.areSearchResultsValid()) {
    aryResults = scapi.getSearchResults().Results;

  //*** Here we create the HTML to render the results list.
  //*** See the createRowHtml() function for details.
    strResultsHtml = '<table cellpadding="0" cellspacing="0" border="0" width="100%">';


      for (intResult = 0; intResult < aryResults.length; intResult++) {

      //gmap
      a = intResult + 1;
		title  = '<b>'+a+'. </b>';
		var authors = new Array();
		var res = aryResults[intResult]
		if (res.authlist)
		{
			authors = aryResults[intResult].authlist.split(" | ");
			for(var auth=0; auth < authors.length-1; auth++)
			{
				title += authors[auth]+' , ';
				if(auth == 6)
				{
					title += '..., ';
					break;
				}
			}
			title += authors[authors.length-1]+'<br>';
		}

		title += '<b>'+aryResults[intResult].title+'</b><br>';
		title += '('+aryResults[intResult].pubdate+') '+aryResults[intResult].sourcetitle;
		title += ', '+aryResults[intResult].vol;
		title += ' pp. '+aryResults[intResult].page+'<br>';
		title += ' <a href="'+aryResults[intResult].inwardurl.replace("record",  "citedby")+'">Cited : '+aryResults[intResult].citedbycount+' times</a><br>';;
		if(aryResults[intResult].doi != '')
		{
			title += '<a href="http://dx.doi.org/'+aryResults[intResult].doi+'">view fulltext</a>';
		}
		title += '<br><br>';

		var idx =  intResult;

		//map.clearOverlays();
		CreateAddressBalloon (aryResults[intResult].affiliations, title, intResult, firstResult, null, retryCount);

		firstResult = false;
		retryCount = 0;

		//render results
		//strResultsHtml += createRowHtml(aryResults[intResult], ++intResult);
		strResultsHtml += createRowHtml(aryResults[intResult], intResult + 1);
    }
    gmm.refresh();

    strResultsHtml += '</table>';

    document.getElementById('divResults').innerHTML = strResultsHtml;
  } else {
  	alert ('An error occured. Error code: 001.');
  }
}

function callbackError() {
  alert('An error occured. Error code: 002.');
  callback();
}

function displaySearchQuery() {
  var objInSubjectArea = document.getElementById('divInSubjectArea');
  var objSinceYear = document.getElementById('divSinceYear');

  if (document.frmSearch.selSubjectArea.value != '') {
    objInSubjectArea.innerHTML = '<br>in ' + document.frmSearch.selSubjectArea.options[document.frmSearch.selSubjectArea.selectedIndex].text;
  } else {
    objInSubjectArea.innerHTML = '<br>in all subject areas';
  }

  if (intFromYear() != -1) {
     objSinceYear.innerHTML = '<br>(' + (intFromYear() + 1) + ' - ' + intCurrentYear + ')';
   } else {
     objSinceYear.innerHTML = '<br>(all years)';
   }
}

function intFromYear() {
  var intYear;

  if (document.frmSearch.selPeriod.value != '') {
    intYear = intCurrentYear - document.frmSearch.selPeriod.value;
  } else {
    intYear = -1;
  }

  return intYear;
}

function createRowHtml(aryResult, intResult) {
  var strReturn = '';
  var strBackgroundColor = '#eeeeee';

  strBackgroundColor = (intResult % 2) ? '#eeeeee' : '#ffffff';

  var strScopusIDVariables = '';

  if (aryResult['doi'] != '') {
    strScopusIDVariables += '&doi=' + aryResult['doi'];
  }
  if (aryResult['eid'] != '') {
    strScopusIDVariables += '&eid=' + aryResult['eid'];
  }
  if (aryResult['scp'] != '') {
    strScopusIDVariables += '&scp=' + aryResult['scp'];
  }


  var strScopusRecordLink = 'forwardRecord.php?partnerID=Ue3HfjoP' + strScopusIDVariables;

  var strResult = '';

  if (intResult < 10) {
    strResult = '&nbsp;' + intResult;
  } else {
    strResult = intResult + '';
  }

  strReturn += '<tr><td style="padding: 10px; color: #0f215c; background-color: ' + strBackgroundColor + ';">';
  strReturn += '<table cellpadding="0" cellspacing="0" border="0">';
  strReturn += '<td valign="top" align="right"><b>' + strResult + '.&nbsp;</td><td colspan="2" style="padding-bottom: 8px;"><b><a href="' + strScopusRecordLink + '" target="_blank" alt="Click to view this article" title="Click to view this article">' + aryResult['title'] + '</a></b>';

  strReturn += '<br><i>';
if (aryResult['firstauth'] != '') {
	strReturn += aryResult['firstauth'];
}
if (aryResult['pubdate'] != '') {
	strReturn += ' (' + aryResult['pubdate'] + ')';
}
if (aryResult['sourcetitle'] != '') {
	strReturn += ', ' + aryResult['sourcetitle'];
}
if (aryResult['vol'] != '') {
	strReturn += ', Volume ' + aryResult['vol'];
}
if (aryResult['issue'] != '') {
	strReturn += ', Issue ' + aryResult['issue'];
}
if (aryResult['issue'] != '') {
	strReturn += ', Pages ' + aryResult['page'];
}
strReturn += '</i></td></tr>';

  var strCitedByCountHtml = '&nbsp;';

  if (aryResult['citedbycount'] != '') {
    var strScopusCitedLink = 'forwardCitedby.php?partnerID=Ue3HfjoP' + strScopusIDVariables;
    strCitedByCountHtml = '<span class="txtSmall"><nobr><b>Cited by:&nbsp;</b></nobr></span></td><td valign="top"><span class="txtSmall"><b><a href="' + strScopusCitedLink + '" target="_blank" alt="Click to view all documents that cite this article" title="Click to view all documents that cite this article">' + addCommas(aryResult['citedbycount']) + '</a></b></span>';
  }

  strReturn += '<tr><td>&nbsp;</td><td valign="top" width="1%">' + strCitedByCountHtml;

//if (!aryResult['abstract']) aryResult['abstract'] = "";
// if ((aryResult['abstract'] + '').length > 0) {
//   strReturn += '<div id="divAbstractLink" style="float: right;"><a href="javascript:toggleAbstract(\'' + aryResult['scp'] + '\');" id="linkAbstract' + aryResult['scp'] + '" class="txtSmall">Show abstract<img src="images/arrowDown.gif" width="12" height="12" border="0" hspace="5" align="absmiddle"></a></div>';
//}

  strReturn += '</td></tr>';
  strReturn += '</table></div>';

//  strReturn += '<div id="divAbstract' + aryResult['scp'] + '" style="display: none;" class="divAbstract txtSmall"><b>Abstract:</b><br>' + aryResult['abstract'] + '</div>';


//*** Uncomment these lines to render all available variables
//	for (var strString in aryResult) {
//		strReturn += strString + ': ' + aryResult[strString] + '<br>';
//	}
  strReturn += '</td></tr>';

  return strReturn;
}

function showScapi() {
  document.getElementById('scapi').style.display = 'block';
}

function toggleAbstract(strAbstractId) {
  var objAbstract = document.getElementById('divAbstract' + strAbstractId);
  var objLinkAbstract = document.getElementById('linkAbstract' + strAbstractId);

  if (objAbstract.style.display == 'none') {
    objAbstract.style.display = 'block';
    objLinkAbstract.innerHTML = 'Hide abstract<img src="images/arrowUp.gif" width="12" height="12" border="0" hspace="5" align="absmiddle">';
  } else {
    objAbstract.style.display = 'none';
    objLinkAbstract.innerHTML = 'Show abstract<img src="images/arrowDown.gif" width="12" height="12" border="0" hspace="5" align="absmiddle">';
  }
}


function toggleAbout() {
  var objAboutMoreContent = document.getElementById('divAboutMoreContent');
  var objAboutMoreLink = document.getElementById('divAboutMoreLink');
  var objAboutLessLink = document.getElementById('divAboutLessLink');

  if (objAboutMoreContent.style.display == 'none') {
    objAboutMoreContent.style.display = 'block';
    objAboutMoreLink.style.display = 'none';
  objAboutLessLink.style.display = 'block';
} else {
    objAboutMoreContent.style.display = 'none';
    objAboutMoreLink.style.display = 'block';
  objAboutLessLink.style.display = 'none';
}
setMapPosition();
}


function toggleContact() {
  var objContactContent = document.getElementById('divContactContent');
  var objContactLink = document.getElementById('divContactLink');

  if (objContactContent.style.display == 'none') {
    objContactContent.style.display = 'block';
    objContactLink.innerHTML = '<img src="images/arrowDown.gif" width="12" height="12" border="0" align="absmiddle" style="margin: 6px;"><b>Contact us</b></a>';
  } else {
    objContactContent.style.display = 'none';
    objContactLink.innerHTML = '<img src="images/arrowRight.gif" width="12" height="12" border="0" align="absmiddle" style="margin: 6px;"><b>Contact us</b></a>';
  }
  setMapPosition();
}

function toggleRecommend() {
  var objRecommendContent = document.getElementById('divRecommendContent');
  var objRecommendLink = document.getElementById('divRecommendLink');

  if (objRecommendContent.style.display == 'none') {
    objRecommendContent.style.display = 'block';
    objRecommendLink.innerHTML = '<img src="images/arrowDown.gif" width="12" height="12" border="0" align="absmiddle" style="margin: 6px;"><b>Share Scopus TopCited with a friend</b></a>';
  } else {
    objRecommendContent.style.display = 'none';
    objRecommendLink.innerHTML = '<img src="images/arrowRight.gif" width="12" height="12" border="0" align="absmiddle" style="margin: 6px;"><b>Share Scopus TopCited with a friend</b></a>';
  }
  setMapPosition();
}

function showPublicationPeriodInfo(blnShow) {
  if (blnShow) {
    document.getElementById('divPublicationPeriodInfo').style.display = 'block';
  } else {
    document.getElementById('divPublicationPeriodInfo').style.display = 'none';
  }
}

function showSubjectAreaInfo(blnShow) {
  if (blnShow) {
    document.getElementById('divSubjectAreaInfo').style.display = 'block';
  } else {
    document.getElementById('divSubjectAreaInfo').style.display = 'none';
  }
}

function addCommas(sValue)
{
  var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})');

  while(sRegExp.test(sValue)) {
    sValue = sValue.replace(sRegExp, '$1,$2');
  }

  return sValue;
}

function checkBrowser(browser)
{
var name = navigator.appName.toLowerCase();
return (name == browser);
}

function fixBackground()
{
var mainDiv = document.getElementById("divMainContainer");
if (checkBrowser("netscape"))
{
	mainDiv.style.height = "auto";
	mainDiv.style.overflow = "auto";
}
else if (checkBrowser("microsoft internet explorer"))
{
	mainDiv.style.height = "100%";
}
}

function GetAbsoluteOffset (el, prop)
	{
		var offset = 0;
		while (el)
		{
			offset += el[prop];//alert(offset)
			el = el.offsetParent;
		}
		return offset;
	}

function showMap()
{
	if (mapExpanded == false) {
			loadGMapLarge();

	var mapPosition = document.getElementById('mapPosition');
	var divMap = document.getElementById('map');
	var top = GetAbsoluteOffset (mapPosition, 'offsetTop') - 220;
	divMap.style.display = "block";
	divMap.style.zIndex = "1000";
	divMap.style.borderWidth = "1px";
	divMap.style.borderStyle = "solid";
	divMap.style.borderColor = "#0FC9C7";
	divMap.style.position = "absolute";
	divMap.style.top = top + "px";
	divMap.style.left = GetAbsoluteOffset (mapPosition, 'offsetLeft') + "px";
	divMap.style.width = "650px";
	divMap.style.height = "370px";


	mapExpanded = true;
}
}

function setMapPosition()
{
var mapPosition = document.getElementById('mapPosition');
var divMap = document.getElementById('map');
divMap.style.zIndex = "1000";
divMap.style.position = "absolute";
divMap.style.top = GetAbsoluteOffset (mapPosition, 'offsetTop') + "px";
divMap.style.left = GetAbsoluteOffset (mapPosition, 'offsetLeft') + "px";
}

function rescaleMap()
{
var mapPosition = document.getElementById('mapPosition');
var divMap = document.getElementById('map');
divMap.style.zIndex = "1000";
divMap.style.position = "absolute";
divMap.style.top = GetAbsoluteOffset (mapPosition, 'offsetTop') + "px";
divMap.style.left = GetAbsoluteOffset (mapPosition, 'offsetLeft') + "px";
divMap.style.width = "300px";
divMap.style.height = "150px";
divMap.style.borderWidth = "0px";
loadGMapSmall();
}

function hideMap()
{
	if (mapExpanded) {
		var ua = navigator.userAgent.toLowerCase();
		isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
		if (isIE)
		{
					var dv = document.getElementById('map');
					if (dv)
					{
						rescaleMap();
					}

		}
		else
		{
		if (inDiv == false)
			{
					var dv = document.getElementById('map');
					if (dv)
					{
						rescaleMap();
					}

			}
			else {
				inDiv = false;
			}
		}
		mapExpanded = false;
	}

}
function mapClick()
{
	var ua = navigator.userAgent.toLowerCase();
	isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1));
	if (isIE)
	{inDiv = false;window.event.cancelBubble = true;}
	else {
	inDiv = true;
	}
}

function getRssUrl(strSearchString)
{
	var rss = document.getElementById("rss");
	rss.href="rss.asp?search=" + strSearchString;
}

