﻿//<![CDATA[

var rootUrl = "";
var lowerCaseLocation = location.href.toLowerCase();
if (lowerCaseLocation.indexOf("cksui") != "-1") {
	rootUrl = "/cksui";
}

sitePrefix = "";

function addEvent(elm, evType, fn, useCapture) {
	if (elm.addEventListener) {
		elm.addEventListener(evType, fn, useCapture);
		return true;
	}
	else if (elm.attachEvent) {
		var r = elm.attachEvent('on' + evType, fn);
		return r;
	}
	else {
		elm['on' + evType] = fn;
	}
}

function addLoadEvent(func) {
    var oldonload = window.onload;
	if (typeof window.onload != 'function') {	   
		window.onload = func;
	}
	else {
		window.onload = function() {	
			oldonload();
			func();
		}
	}
}

function addUnloadEvent(func) {
    var oldonunload = window.onunload;
	if (typeof window.onunload != 'function') {	   
		window.onunload = func;
	}
	else {
		window.onunload = function() {	
			oldonunload();
			func();
		}
	}
}

function getClassName() 
{
	var pattern = new RegExp("msie");
	var browser = navigator.userAgent.toLowerCase();
	
	if(browser.search(pattern) != '-1') 
	{
		if(window.opera)
		{
			return "class";
		}
		else 
		{
			return "className";
		}
	}
	else 
	{
		return "class";
	}
}

function getHTTPObject() {
	var request = null;
	
	if (typeof(XMLHttpRequest) == 'undefined') {
		try {
			request = new ActiveXObject('Msxml2.XMLHTTP');
		}
		catch(e) {
			try {
				request = new ActiveXObject('Microsoft.XMLHTTP');
			}
			catch(ee) { }
		}
	}
	else {
		request = new XMLHttpRequest();
	}
	
	return request;
}

var screenHttp = getHTTPObject();

function handleScreenSubmit() {
    try
    {
        if (screenHttp.readyState == 4) {
            if (screenHttp.status == 200) {
                // We don't need to return anything to the browser in this case...
            }
        }
    }
    catch(e) {}
}

function submitClientProperties() {
    // Removed to reduce the amount of traffic on the site
    // Also this information will be collected by Webtrends
}

function getPageType () {
	var type = "";
		
	if (location.pathname.indexOf("scenario") != "-1") {
		type = "Scenario";
	}
	else {
		type = "Guidance";
		
	}
	
	return type;
}

function getPageIdForCookie() {
	var _Return = "";	
	
	var type = getPageType();
	
	// Get GuidanceId from QueryString
	var GuidanceId_Start = location.href.indexOf(rootUrl, 8) + 1 + rootUrl.length;   // Start 8 characters in to avoid the slashes from 'http://', 
	var GuidanceId_End = location.href.indexOf("/", GuidanceId_Start);                              // Find index of end of guidance ID
	var GuidanceId = location.href.substr(GuidanceId_Start, GuidanceId_End - GuidanceId_Start);	
	
	_Return = location.href.substr(GuidanceId_Start, location.href.length - GuidanceId_Start);
//	// Get 2nd parameters from QueryString
//	if (type == "Scenario") {
//		// Get ScenarioId from QueryString
//		var ScenarioId_Start = location.href.indexOf("scenario/", GuidanceId_End) + 9;	
//		var ScenarioId = location.href.substr(ScenarioId_Start, location.href.length - ScenarioId_Start);
//	
//		_Return = type + "_" + GuidanceId + "_" + ScenarioId;		
//	}	
//	else if (type == "Guidance") {
//		// Get TypeId from QueryString for both Guidance
//		var TypeId_Start = location.href.indexOf("extended_information/", GuidanceId_End) + 21;
//		var TypeId = location.href.substr(TypeId_Start, location.href.length - TypeId_Start);
//		
//		_Return = type + "_" + GuidanceId + "_" + TypeId;
//	}
		
	return _Return;	
}

function changeExpandState(element) {
	var oElement = document.getElementById(element);
	
	var action = "";
	
	if (oElement != null) {
		if (oElement.getAttribute(getClassName()).indexOf("hidden") != -1 ) {
			action = "add";
		}
		else {
			action = "remove";
		}	
	}
	
	changeExpandStateWithAction(action, element);
}

function changeExpandStateWithAction(action, element) {
	var pageId = getPageIdForCookie();							  
	var pageCookie = getCookie(pageId);
		
	if (pageCookie != null) {
		var nodes = pageCookie.split(",");
		var boolInArray = false;
		var cookieValue = "";
		
		for (var i = 0; i < nodes.length; i++) {
			// Loop through nodes
			if(nodes[i] == element) {
				if (action == "remove") {
					nodes[i] = '';				
				}
				boolInArray = true;
			}
			
			if (nodes[i] != '') {
				if (i > 0 && cookieValue != "") {
					var comma = ",";
				}
				else {
					var comma = "";
				}
				
				cookieValue += comma + nodes[i];
			}
		}
		
		if (!boolInArray) {
			cookieValue += "," + element;
		}
		
		if (cookieValue == '') {
			deleteCookie(pageId);
		}
		else {
			setCookie(pageId, cookieValue);
		}
	}
	else {
		setCookie(pageId, element);
	}
}

function expandNodes()
{
	var pageCookie = getCookie(getPageIdForCookie());
	var type = getPageType();
	
	if (pageCookie != null) {
		var nodes = pageCookie.split(",");
		
		if (type == "Scenario" || type == "Guidance") {
			for (var i=0; i < nodes.length; i++)
			{
				changeElementCssClass("Node" + nodes[i], 'NodeCol', 'NodeExp');
				changeElementCssClass(nodes[i], 'hidden', '');
			}
		}
		else if (type == "ProdigyDrug") {
			for (var i=0; i < nodes.length; i++) {
				changeElementCssClass(nodes[i], 'hidden', '');
				changeExpandImage(nodes[i] + "Click");
			}
		}
	}
}

function changeElementCssClass(element, oldClass, newClass) {
	var oElementToChange = document.getElementById(element);
	
	if (oElementToChange != null){	
	    var originalClassString = oElementToChange.getAttribute(getClassName());
	    var newClassString = "";
	    var classChanged = false;
    	
	    if (originalClassString != null) {	                        // Will an empty class string be returned as null?    
		    var classArray = originalClassString.split(" ");
            
            // Cycle through CSS classes and replace oldClass with new Class
		    for(var i = 0; i < classArray.length; i++) {
			    if (classArray[i] == oldClass) {
				    classArray[i] = newClass;
				    classChanged = true;
			    }
		    }
    		
		    if(!classChanged && oldClass == "") {
		        classArray[classArray.length] = newClass;
		        classChanged = true;
		    }
    		
            // Reconstruct the class string
		    for(var i = 0; i < classArray.length; i++) {
			    //if (i > 0 && i < classArray.length) {
			    //	var space = " ";
			    //}
			    //else {
			    //	var space = "";
			    //}

			    var brokenUpNew = newClassString.split(" ");
               
			    if (brokenUpNew.length > 0) {
				    for (var j = 0; j < brokenUpNew.length; j++) {
					    if (brokenUpNew[j] != classArray[i]) {
					        if (classArray[i] != "") {
						        newClassString += " " + classArray[i];
						    }
					    }
				    }
			    }
			    else {
			        newClassString = classArray[i];
			    }						
		    }				
	    }
	    else if (oldClass == "") {
	        newClassString = newClass;
	        classChanged = true;
	    }
    	
	    if(classChanged) {
	        //alert(oElementToChange.getAttribute('ID'));
	        oElementToChange.setAttribute(getClassName(), newClassString);
	        //alert('changed');
	    }
    	
	    return classChanged;
	}
}

function toggleElementCssClass(element, togglingCssClass) 
{
	toggleElementBetweenCssClass(element, togglingCssClass, '');
}

function toggleTwoElementCssClass(element1, element2, togglingCssClass)
{
    toggleElementCssClass(element1, togglingCssClass);
    toggleElementCssClass(element2, togglingCssClass);
}

function toggleElementBetweenCssClass(element, class1, class2) {

    // Can be used to toggle a CSS class on or off (set alternateCssClass to '').
    var oElementToToggle = document.getElementById(element);
    var cssClass = oElementToToggle.getAttribute(getClassName());

    var pattern = new RegExp(class1);

    if ((cssClass == null) || (cssClass.search(pattern) == "-1")) {
        // Default setting
        changeElementCssClass(element, class2, class1);
    }
    else {
        // Alternate setting
        changeElementCssClass(element, class1, class2);
    }
}

function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if(node == null )
	    node = document;
	if(tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if (pattern.test(els[i].getAttribute(getClassName()))) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

function replaceElementsClass(specClass, newClass)
{
    var elements = new Array();
    var obj;
    var currentClass;
    elements = getElementsByClass(specClass, document, '*');
    for(i=0; i<elements.length; i++)
    {
        currentClass = elements[i].getAttribute(getClassName());
        currentClass = currentClass.replace(" ", "");
        if(currentClass == specClass)
        {
            elements[i].setAttribute(getClassName(), newClass);
            currentClass = elements[i].getAttribute(getClassName());
        }
    }
}

function changeImageSrc(elementId, src) {
	var oImage = document.getElementById(elementId);
	
	oImage.setAttribute("src", src);
}
	
function changeExpandImage(elementId) {
	var imgSrc = document.getElementById(elementId).getAttribute("src");	
	
	if (imgSrc.indexOf("Plus") != -1) {
		changeImageSrc(elementId, rootUrl + "/App_Themes/Global/Images/Minus.gif");
	}
	else {
		changeImageSrc(elementId, rootUrl + "/App_Themes/Global/Images/Plus.gif");
	}
}
	
function Load_changeTextSize() {
    var size = getCookie("stylesheet");
    
    switchStyleSheet(size, false);
}
		
function switchStyleSheet(newSheet, changeCookie) {
	// Get the stylesheet references
	var stylesheets = document.getElementsByTagName("link");
	
	// Loop through the stylesheet array	
	for (var i=0; i < stylesheets.length; i++) {
		if (stylesheets[i].getAttribute("rel").indexOf("style") != -1 && stylesheets[i].getAttribute("title")) {		
			// It is a stylesheet, and it has a title attribute ==> it can be disabled
			stylesheets[i].disabled = true;
			
			if(stylesheets[i].getAttribute("title") == newSheet) {			
				// Re-enable the stylesheet that we want activated
				stylesheets[i].disabled = false;
			}
		}
	}
	
	// Write a cookie to the user's machine storing their font-size preference
	if (changeCookie != false) {
		setCookie("stylesheet", newSheet, '', rootUrl + '/', '', '');
	}
}

function CheckTextSize() {
	var stylesheet = getCookie("stylesheet");
		
	if (stylesheet != null) {
		switchStyleSheet(stylesheet, false);
	}
}

function handleSearchSubmit(f) {
   
    var SearchTerms = document.getElementById('searchBox').value;
    
    if(SearchTerms != "")
    {
        var url = rootUrl + "/search/0/" + SearchTerms;
        location.href = url;
    }
    else
    {
        alert("You have not entered any terms to search for. Please enter something and try again.");
    }
}

function handleAdvancedSearchLink(element)
{
    var searchTerms = document.getElementById(element).value;
    if (searchTerms != "")
    {
        var url = rootUrl + "/search/advanced/" + searchTerms;
    }
    else
    {
        var url = rootUrl + "/search/advanced";
    }
    location.href = url;
}

/* QueryString functions */

function getQueryStringParam(querystring, param) {
	var start = querystring.indexOf(param);
	
	if (start != "-1") {
		var ValueIndex = start + param.length + 1;
		var EndIndex = querystring.indexOf("&", ValueIndex);
		if (EndIndex != "-1") {
			var _Return = querystring.substr(ValueIndex, EndIndex - ValueIndex);
		}
		else {
			var _Return = querystring.substr(ValueIndex);
		}
	}
	else {
		_Return = null;
	}
	
	return _Return
}

/* Cookie functions */

function getCookie(name)
{
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	
	if (start == -1) {
		return null;
	}
	
	var end = document.cookie.indexOf( ";", len );
	
	if (end == -1) {
		end = document.cookie.length;
	}
	
	return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value, expires, path, domain, secure) {
	var today = new Date();
	today.setTime(today.getTime());
	
	if (expires) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	
	var expires_date = new Date(today.getTime() + (expires));
	
	document.cookie = name+"="+escape(value) + 
		((expires) ? ";expires="+expires_date.toGMTString() : "") + //expires.toGMTString()
		((path) ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "") +
		((secure) ? ";secure" : "");
}

function deleteCookie(name, path, domain) {
	if (getCookie(name)) document.cookie = name + "=" +
			((path) ? ";path=" + path : "") +
			((domain) ? ";domain=" + domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function checkActivedCssClass(element, initStyle)
{
	var obj = document.getElementById(element);
	if (obj != null) 
	{
		var stylesheet = getCookie("stylesheet");
		var activedCssClass = obj.getAttribute(getClassName());
		if(stylesheet != null)
		{
		/*if(stylesheet == "small"){activedCssClass = obj.setAttribute(getClassName(), "smallTSelected");}
		if(stylesheet == "medium"){activedCssClass = obj.setAttribute(getClassName(), "mediumTSelected");}
		if(stylesheet == "large"){activedCssClass = obj.setAttribute(getClassName(), "largeTSelected");}
		if(stylesheet == "xlarge"){activedCssClass = obj.setAttribute(getClassName(), "xlargeTSelected");}*/
			
			switch(stylesheet)
			{
				case "small":
					activedCssClass = obj.setAttribute(getClassName(), "smallTSelected");
					break;
				case "medium":
					activedCssClass = obj.setAttribute(getClassName(), "mediumTSelected");
					break;
				case "large":
					activedCssClass = obj.setAttribute(getClassName(), "largeTSelected");
					break;
				case "xlarge":
					activedCssClass = obj.setAttribute(getClassName(), "xlargeTSelected");
					break;
			}
		}
		else
		{
			activedCssClass = obj.setAttribute(getClassName(), initStyle);
		}
	}
}

function selected(targetElement, selectedCssClass)
{
	var targetObj = document.getElementById(targetElement);
	var targetElementCurrentCssClass = targetObj.getAttribute(getClassName());
	
	if(targetElementCurrentCssClass != selectedCssClass)
	{
	  targetObj.setAttribute(getClassName(), selectedCssClass);
	}
}

function bookmark(url, title)
{
  if((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4))
  {
    window.external.AddFavorite(url, title);
  } 
  else if(navigator.appName == "Netscape")
  {
    window.sidebar.addPanel(title, url, "");
  }
  else
  {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}

/**********************************

    Browser detection functions 
    
***********************************/

function getUserAgent() {
    return navigator.userAgent.toLowerCase();
}

function isMac() {
    var browser = getUserAgent();
    
    if (browser.indexOf("macintosh") != -1) {
        return true;
    }
    else {
        return false;
    }
}

function isFirefox() {
    var browser = getUserAgent();
    
    if (browser.indexOf("firefox") != -1) {
        return true;
    }
    else {
        return false;
    }
}

// Browser detection
var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		},
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari",
		    versionSearch: "Version"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.userAgent,
		    subString: "iPhone",
		    identity: "iPhone/iPod"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};
BrowserDetect.init();


/**********************************

    Highlight Google search result 
    
***********************************/

/*
 * This function is just an easy way to test the highlightGoogleSearchTerms
 * function.
 */
function testHighlightGoogleSearchTerms()
{
  var referrerString = "http://localhost:1494/cksui/search?&page=1&q=angina&site=0";
  referrerString = prompt("Test the following referrer string:", referrerString);
  return highlightGoogleSearchTerms(referrerString);
}

/*
 * This function takes a referer/referrer string and parses it
 * to determine if it contains any search terms. If it does, the
 * search terms are passed to the highlightSearchTerms function
 * so they can be highlighted on the current page.
 */
function highlightGoogleSearchTerms(referrer)
{
  // This function has only been very lightly tested against
  // typical Google search URLs. If you wanted the Google search
  // terms to be automatically highlighted on a page, you could
  // call the function in the onload event of your <body> tag, 
  // like this:
  //   <body onload='highlightGoogleSearchTerms(document.referrer);'>
  
  //var referrer = document.referrer;
  if (!referrer) {
    return false;
  }
  
  var queryPrefix = "q=";
  var startPos = referrer.toLowerCase().indexOf(queryPrefix);
  if ((startPos < 0) || (startPos + queryPrefix.length == referrer.length)) {
    return false;
  }
  
  var endPos = referrer.indexOf("&", startPos);
  if (endPos < 0) {
    endPos = referrer.length;
  }
  
  var queryString = referrer.substring(startPos + queryPrefix.length, endPos);
  // fix the space characters
  queryString = queryString.replace(/%20/gi, " ");
  queryString = queryString.replace(/\+/gi, " ");
  // remove the quotes (if you're really creative, you could search for the
  // terms within the quotes as phrases, and everything else as single terms)
  queryString = queryString.replace(/%22/gi, "");
  queryString = queryString.replace(/\"/gi, "");
  
  return highlightSearchTerms(queryString, false);
}

/*
 * This is sort of a wrapper function to the doHighlight function.
 * It takes the searchText that you pass, optionally splits it into
 * separate words, and transforms the text on the current web page.
 * Only the "searchText" parameter is required; all other parameters
 * are optional and can be omitted.
 */
function highlightSearchTerms(searchText, treatAsPhrase, warnOnFailure, highlightStartTag, highlightEndTag)
{
  // if the treatAsPhrase parameter is true, then we should search for 
  // the entire phrase that was entered; otherwise, we will split the
  // search string so that each word is searched for and highlighted
  // individually
  if (treatAsPhrase) {
    searchArray = [searchText];
  } else {
    searchArray = searchText.split(" ");
  }
  
  if (!document.body || typeof(document.body.innerHTML) == "undefined") {
    if (warnOnFailure) {
      alert("Sorry, for some reason the text of this page is unavailable. Searching will not work.");
    }
    return false;
  }
  
  var bodyText = document.body.innerHTML;
  for (var i = 0; i < searchArray.length; i++) {
    bodyText = doHighlight(bodyText, searchArray[i], highlightStartTag, highlightEndTag);
  }
  
  document.body.innerHTML = bodyText;
  return true;
}

/*
 * This is the function that actually highlights a text string by
 * adding HTML tags before and after all occurrences of the search
 * term. You can pass your own tags if you'd like, or if the
 * highlightStartTag or highlightEndTag parameters are omitted or
 * are empty strings then the default <font> tags will be used.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) 
{
  // the highlightStartTag and highlightEndTag parameters are optional
  if ((!highlightStartTag) || (!highlightEndTag)) {
    highlightStartTag = "<font style=''>";
    highlightEndTag = "</font>";
  }
  
  // find all occurences of the search term in the given text,
  // and add some "highlight" tags to them (we're not using a
  // regular expression search, because we want to filter out
  // matches that occur within HTML tags and script blocks, so
  // we have to do a little extra validation)
  var newText = "";
  var i = -1;
  var lcSearchTerm = searchTerm.toLowerCase();
  var lcBodyText = bodyText.toLowerCase();
    
  while (bodyText.length > 0) {
    i = lcBodyText.indexOf(lcSearchTerm, i+1);
    if (i < 0) {
      newText += bodyText;
      bodyText = "";
    } else {
      // skip anything inside an HTML tag
      if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
        // skip anything inside a <script> block
        if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
          newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
          bodyText = bodyText.substr(i + searchTerm.length);
          lcBodyText = bodyText.toLowerCase();
          i = -1;
        }
      }
    }
  }
  
  return newText;
}

//Show/hide layers
function showHideLayers()
{
    var i,p,v,obj,args=showHideLayers.arguments;
    for (i=0; i<(args.length-2); i+=3) 
    with (document) if (getElementById && ((obj=getElementById(args[i]))!=null)) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
    }


//]]>
