// to disable links on demo monographs, e.g. onclick="return notAvailable()"  -DS

function showConditionMonograph(loc) {
	NewWin2(loc);
}

function notAvailable () {
	alert("This feature is disabled in the demo version.");
	return false;
}

function notImplemented() {

	alert("Software Engineering has not yet implemented this function");
}

function doPatientVersion() {
	notImplemented()
}

 function NewWin(url, scrollbars) {
  url+="?printversion=true"
  var CMWindow=open(url,"Destination","top=0,left=0,toolbars=0,statusbar=0,menubar=0,scrollbars=" + scrollbars + ",resizable=0,width=550,height=400");
  if (CMWindow.focus != null) {
    CMWindow.focus()
  }
}



 function NewWin2(url, scrollbars, isPubMed) {
 if(!isPubMed){ // DS: This can break custom PubMed links, so making it conditional.
 	url+="?printversion=true";
 }
 var  CMWindow=open(url,"_blank",'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=780,height=530');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
}

 function NewWinMono(url, scrollbars) {
 url+="?printversion=true"
 var CMWindow=open(url,"brandsSearch",'top=0,left=300,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=780,height=530');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
}




 function NewWinSearch(url, scrollbars) {
var  CMWindow=open(url,"brandsSearch",'top=300,left=300,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=780,height=530');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
}
 function NewWinTerms(url, scrollbars) {
var  CMWindow=open(url,"_blank",'top=0,left=0,toolbar=no,status=no,scrollbars=no,location=no,menubar=no,resizable=no,directories=no,width=450,height=380');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
return(CMWindow)
}

 function NewWin3(url, scrollbars) {
 url+="?printversion=true"
 var CMWindow=open(url,"_blank",'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=760,height=580');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
return(CMWindow)
}


 function NewWin4(url, scrollbars,name) {
 
 if (typeof(name)=="undefined") {
 	name="_blank"
 }
 
var  CMWindow=open(url,name,'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=760,height=580');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
  
   if (CMWindow.opener == null) { 
         CMWindow.opener = window  
      }


return(CMWindow)
}

 function NewWinBottomline(url, scrollbars,name) {
 
 if (typeof(name)=="undefined") {
 	name="_blank"
 }
 
var  CMWindow=open(url,name,'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=790,height=580');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
  
   if (CMWindow.opener == null) { 
         CMWindow.opener = window  
      }


return(CMWindow)
}

 function NewWinNudged(url, scrollbars,name) {
 
 if (typeof(name)=="undefined") {
 	name="_blank"
 }
 
 var  CMWindow=open(url,name,'top=0,left=40,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=760,height=580');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
  
   if (CMWindow.opener == null) { 
         CMWindow.opener = window  
      }


return(CMWindow)
}


 function NewWinPrint(url, scrollbars,name) {
 
 if (typeof(name)=="undefined") {
 	name="_blank"
 }
 
 var CMWindow=window.open(url,name,'top=0,left=40,toolbar=yes,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=760,height=580');

//if (CMWindow) {

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
  
   if (CMWindow.opener == null) { 
         CMWindow.opener = window  
      }
//}

return(CMWindow)
}


 function NewWin4parent(url, scrollbars,name) {
 
 if (typeof(name)=="undefined") {
 	name="_blank"
 }
 
  CMWindow=parent.open(url,name,'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=760,height=580');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
  
   if (CMWindow.opener == null) { 
         CMWindow.opener = window  
      }


return(CMWindow)
}



function NewWin5(url, scrollbars) {
  var CMWindow=window.open(url,"_blank",'top=0,left=0,toolbar=yes,status=no,scrollbars=yes,location=no,menubar=yes,resizable=yes,directories=no,width=760,height=380');

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
return(CMWindow)
}


 function NewWinSmall(url, scrollbars) {
	var width= 500;
	var height=350;
  CMWindow=open(url,"Definition",'top=0,left=0,toolbar=no,status=no,scrollbars=no,location=no,menubar=no,resizable=yes,directories=no,width=' + width+',height='+height);

if (CMWindow.focus != null) {
    CMWindow.focus()
  }
}

 function NewWinChecker(url, scrollbars) {
 	try {
		var CMWindow=open(url,"_blank",'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=850,height=650');

		if (CMWindow.focus != null) {
			CMWindow.focus()
		  }
	 }
	  catch (e) {
	  	// Pop-up blocker
	  }
}

 function NewWinFull(url, scrollbars) {
	var width= screen.availWidth-6;
	var height=screen.availHeight-32;
	CMWindow=open(url,"_blank",'top=0,left=0,toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width=' + width+',height='+height);

	CMWindow.resizeTo ( screen.availWidth, screen.availHeight);
	if (CMWindow.focus != null) {
		CMWindow.focus()
	}
}


function openChecker(mode) {
	mode = mode || "int";
	var files = {
		"int":"interaction-advanced.asp",
		"dep":"depletions.asp",
		"drugs":"depletions-drugs.asp",
		"formulary":"formulary.asp"
	}

	var url = '/tools/InteractionHTML/'+files[mode];
	NewWinChecker(url);
}


function getSearchTerm(name){
 name += "";
 name = name.replace(/ seed|herb| leaf| leaves| extract| powder| fruit| flower| complex| oil| syrup| root| blend/gi, "");
 name = name.replace(/^\d+%/, "");
 name = name.replace(/\s+/g, " ");
 return trim(name);
}

function trim (str){
 str += "";
 str = str.replace(/^\s+/, ""); 
 str = str.replace(/\s+$/, "");
 return str;
}



function doQuickSearch(item) {
	item= item.replace(/~/gi,"'");

	item= item.replace(/&/gi,"");
	
	item=item.replace(/ and /gi," ");
	
	if (item.indexOf(" - ")>0) {
		item = item.substring(0,item.indexOf(" - "));
	}

	if (item.indexOf("(")>0) {
		item = item.substring(0,item.indexOf("("));
	}

	item=getSearchTerm(item);


	
	//document.location = 
	NewWinSearch("../../search_brands.asp?text=" +item);
	return(false);

}



function doQuickSearchOld(item) {
	item= item.replace(/~/gi,"'");

	item= item.replace(/&/gi,"");
	
	item=item.replace(/ and /gi," ");
	
	if (item.indexOf(" - ")>0) {
		item = item.substring(0,item.indexOf(" - "));
	}

	if (item.indexOf("(")>0) {
		item = item.substring(0,item.indexOf("("));
	}
	item= item.replace(/extract /gi,"");
	

	item= item.replace(/ /gi," or ");
	item = item.replace(/or\s*or/gi,"or");
	
	item = item.replace(/or $/gi,"");
	item = item.replace(/or$/gi,"");

	
	//document.location = 
	NewWinSearch("../../search_brands.asp?text=" +item);
	return(false);

}
function doterms (){
	termswin = NewWinTerms ("nsclickwrap.asp")
}

function closeterms() {

	termswin.close();

}

function getCookieValue (name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	var str = "";
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {
			try {
				str = decodeURIComponent(c.substring(nameEQ.length,c.length));
			}
			catch (e) {
				return "";
			}
			return str;
		}
	}
	return str;
}

function getSpecialArgs() {
	//var ck = document.cookie
	//var specialArgs="";
	
	//ck = decodeURI(ck);
	
	// DS: new implementation using cookie set with pub med parameters from database
	
	var specialArgs = getCookieValue("PubMedCookie");
		
	return specialArgs ? "&"+specialArgs : "";
	
	/*********************** DS: not used, but retained for reference ***********
	
	if (ck.indexOf("User=IPAccessAllowed%3AYale")>=0){
		specialArgs+="&otool=yalelib"
	}
	
	if (ck.indexOf("User=IPAccessAllowed%3ALehigh")>=0){
		specialArgs+="&holding=palvhlib_fft"
	}
	
	if (ck.indexOf("User=IPAccessAllowed%3ASarasota")>=0){
		specialArgs+="&holding=fluzesllib"
	}
	
	if (ck.indexOf("User=IPAccessAllowed%3AVanderbilt")>=0){
		specialArgs+="&holding=vandylib"
	}

	if (ck.indexOf("User=IPAccessAllowed%3AMassachusetts+College+of+Pharmacy")>=0){
		specialArgs+="&holding=mcplib"
	}
	if (ck.indexOf("User=IPAccessAllowed%3AWake+Forest+U")>=0){
		specialArgs+="&holding=wfusmlib"
	}
	if (ck.indexOf("User=IPAccessAllowed%3AUniversity+of+Virginia")>=0){
		specialArgs+="&holding=uvirlib"
	}	
	if (ck.indexOf("User=IPAccessAllowed%3AUCONN")>=0){
		specialArgs+="&holding=uchclib"
	}	
	if (ck.indexOf("User=IPAccessAllowed%3AMaine+Medical+Center")>=0){
		specialArgs+="&holding=memclib_fft"
	}	
	if (ck.indexOf("User=IPAccessAllowed%3AKaiser+Permanente")>=0){
		specialArgs+="&holding=cakpkclib"
	}	
		
	return(specialArgs);
	
	***************************************************/
}

function getCustomCitationLink  (url, id, params) {
	var str = url +"?pmid="+id;
	if(params) {
		str += "&"+params;
	}
	return str;
}

function vcuCitation (url, arg, params) {
	// DS: Cusotm citation function for VCU
	
	params = getCookieValue("PubmedParams"); // DS: note "Pubmed" with a lower case m.
	
	var str =  url +"?" + params + "&" + "id=pmid:"+encodeURIComponent(arg);
	
	
	return str;
}

function doPubMedLink (arg) {	
	var url = getCookieValue("CitationURL");
	if (url && (url !="null")){
		var funcName = getCookieValue("CitationFunction");
		var params = getCookieValue("CitationParams");
		var func = getCustomCitationLink;
		if(funcName){
			func = window[funcName] || func;
		}
		
		NewWin2(func(url, arg, params), "", true);
	}
	else {
		var specialArgs =getSpecialArgs();
		NewWin2("http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids="+ arg +"&dopt=Abstract" + specialArgs, "", true);
	}
}

function doRefLink (arg) {

	var specialArgs =getSpecialArgs();
	
	while (arg.substring(0,1) == " ") {
	arg=arg.substring(1)

	}

	var loc = document.location.href
	var relref=""
	if ( loc.indexOf("/news/")>1  )  {
		relref="../../"
	}

	else if (loc.indexOf("glossary/")>1   )
		relref="../"
	else
		relref="../../"


	if (arg.length>2) {
		if (arg.substring(0,2)=="PM")
			//NewWin2("http://www.ncbi.nlm.nih.gov/entrez/query.fcgi?cmd=Retrieve&db=PubMed&list_uids="+ arg.substring(3) +"&dopt=Abstract" + specialArgs);
			doPubMedLink(arg.substring(3));
		else	if (arg.substring(0,3)=="CN:")
			findAndLinkCondition(arg.substring(4) ); 

		else if (parseInt(arg).toString() == arg)
			NewWin2(relref+"glossary/glossary" + arg +".asp");
		else {
		ShowMonographInfo(arg, "herb", "");

		}
	}
		else if (parseInt(arg).toString() == arg)
			NewWin2("http://naturalstandard.com/monographs/glossary/glossary" + arg +".asp");
		else {
			if (window.event) {
				//alert (window.event.srcElement.innerText);
			
				ShowMonographInfo(arg, "herb",window.event.srcElement.innerText)
			}
			else {
				ShowMonographInfo(arg, "herb", "");
			}

		}	
}
function showGrading () {
	NewWin2("../../grading.html");
}

function showEvidenceTableInfo(item) {
	switch (item) {
case "Condition" :
page="COLUMN1"
break;
case "Design" :
page="COLUMN2"
break;
case "Author" :
page="COLUMN3"
break;
case "N" :
page="COLUMN4"
break;
case "Significant" :
page="COLUMN5"
break;
case "Quality of Study" :
page="COLUMN6"
break;
case "Benefit" :
page="COLUMN7"
break;
case "RiskReduction" :
page="COLUMN8"
break;
case "Number" :
page="COLUMN9"
break;

case "Comments" :
page="COLUMN10"
break;

} 

	NewWin2("../../explanation_columns.html#"+ page);


}
function conditionShowGrading () {
	NewWin2("/naturalstandard/grading.html"); // update to use root relative path so demo will work
}


function ShowMonograph (url,kind) {
	parent.location="monographs/monoframeset.asp?monograph=" +escape(url)

}

function ShowPatientMonograph (url,kind) {
	//parent.location="monoframeset.asp?monograph=" +escape(url)
	NewWinBottomline("monoframeset.asp?monograph=" +escape(url));

}


function ShowMonographInfo(url,kind,title) {

	if (title.indexOf("(")>0)
		title=title.substring(0,title.indexOf("("));

	var filename ="";

	try {
		filename = url.substr(url.lastIndexOf("/")+1);
	}
	catch (e) {
	}
	

	var targetURL = "/naturalstandard/monographinfo.asp?title="+escape(title)+"&file=" +escape( filename);

	NewWin4(targetURL,false,"monoinfo");
}

function ShowPatientMonographInfo(url,kind,title) {

	if (title.indexOf("(")>0)
		title=title.substring(0,title.indexOf("("));


	NewWin4("/naturalstandard/patient-monographinfo.asp?title="+escape(title));
}

function conditionShowMonographInfo(url,kind,title) {

	if (title.indexOf("(")>0)
		title=title.substring(0,title.indexOf("("));


var filename ="";

	try {
		filename = url.substr(url.lastIndexOf("/")+1);
	}
	catch (e) {
	}
	
	w= NewWinNudged("/naturalstandard/monographinfo.asp?title="+escape(title)+"&file=" +escape( filename));
	
	w. nsMainWindow = opener;
	
}



function directShowMonographInfo (url,kind,title) {
	var filename ="";

	try {
		filename = url.substr(url.lastIndexOf("/")+1);
	}
	catch (e) {
	}


	document.location.href="/naturalstandard/monographinfo.asp?title="+escape(title) +"&file=" +escape( filename);;


}


function conditionShowMonograph (url,kind) {
	opener.parent.location="monographs/monoframeset.asp?monograph=" +escape(url)
	self.close()
}

/*
function openerShowMonograph (url,kind,patientVersion) {
	if (patientVersion)
		opener.parent.location="/naturalstandard/monographs/monoframeset.asp?monograph=" +escape(url) +"&patientVersion=" +escape(patientVersion);
	else
		opener.parent.location="/naturalstandard/monographs/monoframeset.asp?monograph=" +escape(url) 
	if (url.indexOf("news/")>=0)
		opener.parent.left_nav.location.href ="/naturalstandard/left_nav.html";

	self.close()
}
*/
function openerShowMonograph (url,kind,patientVersion) {
	var mainWindow
	
	mainWindow = (typeof(window.nsMainWindow)=="undefined")?window.opener:window.nsMainWindow

	
	if (patientVersion)
		mainWindow=window.open("/naturalstandard/monographs/monoframeset.asp?monograph=" +escape(url) +"&patientVersion=" +escape(patientVersion), "nsMain");
	else
		mainWindow=window.open("/naturalstandard/monographs/monoframeset.asp?monograph=" +escape(url) , "nsMain");

	/*
	if (url.indexOf("news/")>=0)
		mainWindow.parent.left_nav.location.href ="/naturalstandard/left_nav.html";

	*/
		mainWindow.focus();
	
		
	// CTW -- keep window open now
	//self.close()
}


/* GAS - Added function for displaying CONSUMER selection in main frame vs. opening in New Window */

function consumerShowMonograph (url,kind,patientVersion) {


	var goHereYoungMan	= (url);
	
	document.location.href= goHereYoungMan;


}



function ShowCondition (name,type,id) {
	name= name.replace(/ /g,"%20")
	NewWin4parent("/conditioninfo.asp?condition=" +name+"&conditionId=" + id +"&type="+type,"vertical")
}

function findAndLinkCondition(conditionName) {

	NewWin4("../../conditionbyName.asp?condition=" +escape(conditionName),"vertical")



}

function monographInit() {
	fixFramesetHack();
		
}



function setMonoFrameset () {


	var navPage = "mono_left_nav.html"
if (typeof(monographCategory) !="undefined") {

	if (monographCategory=="patient-herbs") {
		navPage = "mono_left_nav_herbal.html"

	}

	if (monographCategory=="patient-modalities") {
		navPage = "mono_left_nav_modal.html"

	}

	if (monographCategory=="spanish-patient-herbs") {
		navPage = "../mono_left_nav_herbal_spanish.html"

	}

		
}

if (top.left_nav)
	top.left_nav.location.href = "../" + navPage;


}

function setDefaultFrameset () {}


function fixFramesetHack() {
	var loc = document.location.href
	
	if ( (loc.indexOf("/herbssupplements") >0) ||
	     (loc.indexOf("/alternativemodalities") >0) ||
	     (loc.indexOf("/specialdiets") >0) ||
	     (loc.indexOf("/foreignlanguage") >0) ||
	     (loc.indexOf("/vitaminsminerals") >0)) {

	// set to Monograph frameset
	setMonoFrameset();
	}
	else {
	setDefaultFrameset()

	}

}


function addEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  }
}

function addPrintEmailLinks () {
	
	var path = encodeURIComponent(location.pathname);
	var monoTitle = encodeURIComponent(document.title);
	
	var params = "?title="+monoTitle+"&file="+path;
	
	var links = "<ul id='email-print-links'>";
	
	links += '<li><a href="/monographs/mono-email.asp'+params+'" onclick="emailWin(this.href); return false">Email</a></li>';
	
	links += '<li><a href="/monographs/mono-print.asp'+params+'" onclick="printWin(this.href); return false">Print</a></li>';
	
	links += "</ul>";
	
	
	$("body").prepend(links);
	
	if(!inCE()) {
		loadCEData();
	}
}

function loadCEData () {
	loadScript("/scripts/clientside/ce-offerings.js", addCELink);
}

function addCELink () {
	
	var fileName = getFilename();
	
	
	if(CE_OFFERINGS && CE_OFFERINGS[fileName]) {
		var offering = CE_OFFERINGS[fileName];		
		$("#email-print-links").prepend("<li><a href='"+offering+"' onclick='NewWinFull(this.href); return false'>Take CE</a></li>");		
	}
	
}

function inCE () {
	if(parent) {
		var parentPath = parent.location.pathname.toLowerCase();
		return parentPath.match(/^\/ce\//) ? true : false;
	}
	return false;
}

function getFilename () {
	var path = location.pathname.toLowerCase();
	return path.substring(path.lastIndexOf("/")+1, path.indexOf(".asp"));
}

function emailWin (url) {
	newWinGeneric(url, 780, 900);
}

function printWin (url) {
	newWinGeneric(url, 780, 650);
}

function newWinGeneric (url, w, h) {
	
	var winX = window.screenLeft || window.screenX || 0;
	var winY = window.screenTop || window.screenY || 0;
	
	var t = winY + 10;
	var l = winX + 150;
	
	return window.open(url, "_blank", "top="+t+",left="+l+",toolbar=no,status=no,scrollbars=yes,location=no,menubar=no,resizable=yes,directories=no,width="+w+",height="+h);

}

function loadJQuery () {
	
	// DS: Generalizing this so I can use it to load the CE data file
	
	loadScript("/scripts/clientside/jquery-1.3.2.min.js", addPrintEmailLinks);
	
	/*** 
	
	var headElem = document.getElementsByTagName("head")[0];
	var newScript = document.createElement("script");
	
	newScript.type = "text/javascript";
	newScript.src = "/scripts/clientside/jquery-1.3.2.min.js";
	
	newScript.onload = function () {
		if(!newScript.onloadDone) {
			newScript.onloadDone = true;
			addPrintEmailLinks();
		}
	}
	
	newScript.onreadystatechange = function () {
	if (("loaded" === newScript.readyState || "complete" === newScript.readyState ) && ! newScript.onloadDone ) {
		newScript.onloadDone = true; 
		addPrintEmailLinks();
	    }

	}
	
	headElem.appendChild(newScript);
	
	**/
}

function loadScript (scriptLocation, loadHandler) {
	
	// DS: Taken from loadJQuery, above
	
	var headElem = document.getElementsByTagName("head")[0];
	var newScript = document.createElement("script");

	newScript.type = "text/javascript";
	newScript.src = scriptLocation;

	newScript.onload = function () {
		if(!newScript.onloadDone) {
			newScript.onloadDone = true;
			loadHandler();
		}
	}

	newScript.onreadystatechange = function () {
	if (("loaded" === newScript.readyState || "complete" === newScript.readyState ) && ! newScript.onloadDone ) {
		newScript.onloadDone = true; 
		loadHandler();
	    }

	}
		
	headElem.appendChild(newScript);
}

function isMonograph () {
	var path = location.pathname.toLowerCase();
	
	var fileNameRe = /\/[^\/]+\.asp/;
	
	var pathRe = /\/monographs\/(herbssupplements|alternativemodalities|allergies|conditions|foreignlanguage|flashcards|genomics|enviro)\//i;
	
	
	var tocRe = /\/toc_|\/index/i;
	
	
	return fileNameRe.test(path) && pathRe.test(path) && !tocRe.test(path);
}

if(isMonograph()) {

	addEvent(window, "load", function () {loadJQuery(); }, true);
}


// Legacy Scripts from first implementation



// Script courtesy of Project Cool

	browser = (((navigator.appName == "Netscape") && (parseInt(navigator.appVersion) >= 3 )) || ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4 )))

	if ( browser) {
		normal = new Object()
		over = new Object
		blurb = new Object
		
		normal["GRADING"] = new Image();
		over["GRADING"] = new Image();
		normal["GRADING"].src = "/naturalstandard/images/home/grading_system.gif"
		over["GRADING"].src = "/naturalstandard/images/home/grading_system2.gif"
	
		blurb["GRADING"] = "A description of our grading system"
		blurb[2] = ""
		}
		
      function MakeArray(n) {
              this.length = n
              for (var i = 1; i<=n; i++) {
                      this[i] = new Image()
                      }
              return this
      }

	function msover(num) {
			if ( browser) {	
				document.images[num].src = over[num].src
				window.status = blurb[num]
			}
		}

	function msout(num) {
			if ( browser) {
	                  		document.images[num].src = normal[num].src
	                  		window.status = ""
			}	            
		}
