//BEGIN BROWSER/PLATFORM DETECTION/SETTING CALL ACTIONS///////////////////////////////
// check to see if the user is using a supported browser and platform -- if not redirect them
ValidateClient();
// this line writes the style sheet link to the page (<link href='stylesheet.css' ....>) 

document.write(SetCssStyle());


//END CALL ACTIONS////////////////////////////////

//BEGIN BROWSER/PLATFORM DETECTION/SETTING FUNCTIONS////////////////////////////////
// function simply returns a string which represents the type of Browser user has
// currently, we are only checking for 3 types of browser DOMs (latest DOM (IE 5 +, NS 6+), NS4, IE4)
// if a new browser is to be supported, its string name will need to be added to this function, the 
// validBrowsers function, and the SetCSSStyle function
function BrowserType()
{
	var browserType 
	
	if (document.layers) {
		browserType =  "NS4"; 
	}
	else if (document.all && !document.getElementById) {
		browserType = "IE4";
	}
	else if (document.getElementById) {
		browserType = "DOM";
	}
	else {
		browserType = "Unsupported";
	}
	
	return browserType;
}

// function simply returns a string which represents the type of Platform user has
// currently, we are only checking for 2 types of platforms (PCs and Macs, everything else is lumped into Other)
function PlatformType()
{
	var platformType
   	if (navigator.appVersion.indexOf("Mac") != -1) {
	platformType = "Mac";
	}
	else if (navigator.appVersion.indexOf("Win") != -1) {
	platformType = "PC";
	}
	else {
	platformType = "Other";
	}

	return platformType;
}
// this function lists the valid browser types and returns an array with the valid browser names 
function ValidBrowsers()
{
	var arrValidBrowsers = new Array()
	//arrValidBrowsers[0] = "IE4";
	//arrValidBrowsers[1] = "NS4";
	//arrValidBrowsers[2] = "DOM";
	arrValidBrowsers[0] = "DOM";
	
	return arrValidBrowsers;
}

// this function is simply a boolean which will show if the user has a supported browser. will use this
// in combination with the valid platform function to see if we need to redirect user to a page
// which informs them they have an invalid client
function IsValidBrowser()
{
	var validBrowser = false;
	var browserType = BrowserType();
	var arrValidBrowsers = ValidBrowsers();
	var index = 0;
	while (index < arrValidBrowsers.length)
		{
		if (browserType.toString().toLowerCase() == arrValidBrowsers[index].toString().toLowerCase()) {
				validBrowser = true;
			}
		index++;
		}
	return validBrowser;
}
// this function lists the valid browser types and returns an array with the valid browser names 
function ValidPlatforms()
{
	var arrValidPlatforms = new Array()
	arrValidPlatforms[0] = "Mac";
	arrValidPlatforms[1] = "PC";
	arrValidPlatforms[2] = "Other";
	
	return arrValidPlatforms;
}
// this function is simply a boolean which will show if the user has a supported platform. will use this
// in combination with the valid browser function to see if we need to redirect user to a page
// which informs them they have an invalid client
function IsValidPlatform()
{
	var validPlatform = false;	
	var platformType = PlatformType();
	var arrValidPlatforms = ValidPlatforms();
	var index = 0;
	while (index < arrValidPlatforms.length)
		{
		if (platformType.toString().toLowerCase() == arrValidPlatforms[index].toString().toLowerCase()) {
				validPlatform = true;
			}
		index++;
		}
		
	return validPlatform;
}

// if user is using a Platform and Browser not supported then redirect them
function ValidateClient(){
	if (!IsValidBrowser() | !IsValidPlatform()) {	
		if(window.location.href.toLowerCase().indexOf("/design/redesign/error/invalidbrowser.aspx")<0 ){
			window.location.href="/design/redesign/error/InvalidBrowser.aspx";
			//for some reason this line fixes a reference problem.
			if (platformType().toString().toLowerCase()=="Mac"){
				document.write("fix bug");
			}			
		}
				
	}
}

// WritePartialStyle... function checks the user's style cookie and returns a string containing the partial path
// to the style sheet (this string is passed into the SetCssStyle() function -- a partial path is written because
// in SetCssStyle we check to find the users browser & platform combo and based on this direct them to the style sheet
// tailor made for their platform -- only one portion of the path to the style sheet (styles_...) changes
function WritePartialStyleSheetPath()
{
	var partialSSPath = "";
	if(document.cookie.indexOf('style=altstyle')>=0)	{ 
		 partialSSPath = "<link rel='stylesheet' type='text/css' href='/design/redesign/global/css_alt/styles_";
		}
	else {
		partialSSPath ="<link rel='stylesheet' type='text/css' href='/design/redesign/global/css/styles_";
		 }
//	alert(partialSSPath);
	return partialSSPath
}

// SetCssStyle returns a string based on the user's Browser/Platform -- which is the 'dynamic' portion of the CSS filename stylesheet to use according to the user's Browser and Platform
// this value is then written to all HTML pages as their stylesheet link 
function SetCssStyle()
{
	var browserType = BrowserType();
	var platformType = PlatformType();
	var styleSheet = "";
	// stylesheetPath var calls WritePartialStyle... function which checks a cookie to see if the user
	// has selected the alternate style sheet -- accessiblity feature -- and then returns the first portion
	// of the style sheet path. the rest of the stylesheet path is constructed below based on the user's browser and platform.
	var stylesheetPath = WritePartialStyleSheetPath();

	if (platformType=="PC") 
		{
			if (browserType=="DOM"){styleSheet = "DOM";} 
			else if (browserType=="NS4"){styleSheet = "WINNS4";} 
			else if (browserType=="IE4"){styleSheet = "IE4";} 
			else {styleSheet = "DOM";}
		}
	else if (platformType=="Mac") 
		{
			if (browserType=="DOM"){styleSheet = "DOM";} 
			else if (browserType=="NS4"){styleSheet = "MACNS4";} 
			else {styleSheet = "DOM";}
		}
	else 
		{
			styleSheet = "DOM";
		}

	var stylesheetPath =  stylesheetPath + styleSheet + ".css' rel='stylesheet' type='text/css'>";
	
	return stylesheetPath;
}
//END FUNCTIONS////////////////////////////

// BEGIN ACCESSIBILITY DETECTION/SETTING ACTIONS///////////////////////////////
// Two folders hold the style sheets. they are referred to as 'default' and 'altstyle'
// 'default' style(s) are in the css folder. 'altstyle' are in the css_alt folder.
// So we are doing two things. First, checking the user's style sheet preference, which they can control
// by selecting the 'default' or 'altstyle' from the menu options -- this is the work the functions below
// handle. Then we check to find the user's browser and platform (which is what the functions above handle),
// and then direct the user to the approriate style sheets based on their preference and then the browser/platfom he/she is using

// END ACCESSIBILITY DETECTION/SETTING ACTIONS///////////////////////////////

// BEGIN ACCESSIBILITY DETECTION/SETTING FUNCTIONS///////////////////////////////
// check to see if the user has a stylesheet cookie, if not write the default style to the cookie.






 
// write the user's style sheet preference to a cookie
function SetAccessibilityStyle(newstyle)
{			
			var expdate = new Date();
			expdate.setTime(expdate.getTime() + (1000*3600*24*365));
			document.cookie = 'style=' + newstyle + '; expires=' + expdate.toGMTString() + '; path=/';
			//alert ('This style choice will persist for a year unless changed again.\n You may need to reload the page.');
			//self.location = self.location;
			//return newstyle
}
function CheckStyleSheetCookie(){

	if (document.cookie.indexOf('style=altstyle')<0 && document.cookie.indexOf('style=default')<0)	
	{
		SetAccessibilityStyle("default");
	}
}

//END  ACCESSIBILITY DETECTION/SETTING FUNCTIONS////////////////////////////////

// Probably should add a window onload event here to load the rollover images --- window.onload = 
//"MM_preloadImages('../../templates/images/sm_tab_images/sm_ed_on.gif',//'../../templates/images/sm_tab_images/sm_research_on.gif',//'../../templates/images/sm_tab_images/sm_patient_on.gif')"

// IMAGE ROLLOVER FUNCTIONS///////////////////////////////
function LoadImages()
{
	MM_preloadImages("/design/redesign/templates/images/sm_tab_images/sm_ed_on.gif","/design/redesign/templates/images/sm_tab_images/sm_research_on.gif","/design/redesign/templates/images/sm_tab_images/sm_patient_on.gif","/design/redesign/templates/images/lg_tab_images/lg_ed_on.gif","/design/redesign/templates/images/lg_tab_images/lg_research_on.gif","/design/redesign/templates/images/lg_tab_images/lg_patient_on.gif")
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//END IMAGE ROLLOVER FUNCTIONS////////////////////////////////


//START MENU HIDE FIXES

function SOMHideDivs(bShow){
/*
FUNCTION PURPOSE:
This function was built to stop the menus from showing behind form elements in some browsers. Solves the problem by
hiding the elements that should be hidden. 
 
It requires 2 things to work.
1) that all elements that should be hidden are within a <div> tag that has an id attribute specified. 
2) that a hidden field called hidediv be created and populated with the names of the div tags that you want to
	hide. Multiple division tags can be separated by a | charater. 
   
IMPLEMENTATION: 
This function spins through all the form on the page and looks for a hidden field named hiddiv. If found, 
the value in this tag is used to hide all of the <div> tags whose name is found within the tag.
This function will be use primarily with 

DEPENDANCIES:
1) this function looks for the hidediv tag in each form on the page and hides any div tags listed within that form. 
   A new hidediv tag needs to be specified for each form that has elements to hide. 
2) it uses the showSelect function this needs to be included within the page. 	

*/ 
    var sDivs = new String()
	var i=0
	var iEl =0
	var isplit=0
	var sDivHide= new String()
	var arSplitdiv = new Array()
	for (i=0; i<document.forms.length ; i++){
		for (iEl=0; iEl<document.forms[i].elements.length; iEl++){
				
			if(document.forms[i].elements[iEl] != null){
				if(document.forms[i].elements[iEl].name.toLowerCase()=="hidediv"){
					sDivHide =document.forms[i].elements[iEl].value
				}
			}
		}
		if (sDivHide.toString != ""){
			arSplitdiv= sDivHide.split("|")
			if (arSplitdiv.length>0){
				for (isplit=0; isplit<arSplitdiv.length; isplit++){
					showSelect(bShow,arSplitdiv[isplit]);
				}
			}			
		}
	}
}

function showSelect(isOn,divName) {
   var theSelect = null;
   if(document.getElementById) {
      theSelect=document.getElementById(divName);
      if(theSelect) theSelect.style.visibility = isOn ? "visible" : "hidden";
   } else if (document.all) {
      theSelect=document.all(divName);
      if(theSelect) theSelect.style.visibility = isOn ? "visible" : "hidden";
   } else if (document.layers) {
      theSelect=document[divName];
      if(theSelect) theSelect.visibility = isOn ? "show" : "hide";
   }
}

//END MENU HIDE FIXES
//start fixes for open window functions

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
function openWin(url,specs) {
	myWin=open(url,'',specs);
}

//end fixes for open window functions

//start fixes for link rewriting


function golnk(sLink, sTestUrl){
/*
FUNCTION PURPOSE:
This function was created rewrite links based on where the user was within the network so that global links will
work on different sites.  this function uses the getlnk function which does the actual link rewriting. This
function moves the user to the appropriate location based on the environment the user is in. 

PARAMETERS:
+ sLink:	a required parameter. this is the link that should be rewritten.
+ sTestUrl:	an optional paramter. this is a test url that can be used for testing.

IMPLEMENTATION: 
Should be used in the onClick event of a <a> tag. it returns false so that the url listed in the href is not used. 
here is an example: <a href="https://www.cme.ucsf.edu/calendar/" OnClick="return golnk('https://www.cme.ucsf.edu/calendar/');">go to cme.ucsf.edu</a>

DEPENDANCIES:
This function uses getlnk to rewrite the links.

*/
	var sUrl //= new String("") 
	if (sTestUrl ==null){
		sUrl=document.location.href
	}else{	
		sUrl=sTestUrl
	}
//alert(sUrl);
	//document.location.href=getlnk(sLink,sUrl)
	parent.location.href=getlnk(sLink,sUrl)
	return false;
}

function getlnk(sLink){
/*
FUNCTION PURPOSE:
this function rewrites the links based on which development environment they are in. 

PARAMETERS:
+ sLink:	a required parameter. this is the link that should be rewritten.

IMPLEMENTATION: 
This function adds int if the user is in the integration environment or stage if the user is in staging.

DEPENDANCIES:

*/

	var sRtn = new String("") //url to return 
	var sUrl = new String("")  //url to do the evaluation
	sUrl=document.location.href
	if (sUrl.indexOf("https://www.intranet.")<0){
		if (sUrl.indexOf("http://int")>=0){
			sRtn = "http://int" + sLink.slice(7)
		}else if (sUrl.indexOf("http://stage")>=0){		
			sRtn = "http://stage" + sLink.slice(7)
		}else if (sUrl.indexOf("http://dev")>=0){		
			sRtn = "http://dev" + sLink.slice(7)		
		}else{
			sRtn=sLink				
		}
	}else{
		sRtn=sLink		
	}	
	return sRtn
}

//End fixes for link rewriting
//start javascript for printer friendly formatting

//Global variable used reverse PrinterFriendly format

//var RG_BODY_HTML  
//var RG_UCNAV_HTML 
//var RG_MEDNAV_HTML

function OpenPrintWindow(){
	var s = window.location.search
	var d
	if (s ==""){
		d="?"
	}else{
		d="&"
	}
	window.open(window.location + d + "somprint=true")	
}


function ShowPrinterFriendly(){
	//first checks to see if the somprint flag is present. if it is then it reformats 
	//to a printer friendly format.
	
	if (window.location.search.indexOf("somprint=true")>0){
		var sBread = document.getElementById("bread").innerHTML	
		DrawPrintFriendlyUCHeader()
		DrawPrintFriendlyMedSchHeader(sBread)
		DrawPrintFriendlyBody()
		document.getElementById("Medfooter").innerHTML=""
	}
}

function ReversePrinterFriendly(){
	//change back to original 
	document.getElementById("PFDiv").outerHTML=RG_BODY_HTML
	document.getElementById("UCNav").innerHTML=RG_UCNAV_HTML
	document.getElementById("MEDNav").innerHTML=RG_MEDNAV_HTML
}

function DrawPrintFriendlyBody(){
	//string to look for
	var strFind= '#BeginEditable "Content"'
	//get the html in body to keep
	var bodyhtml = GetElementHTMLContainingString(document,"td",strFind)
	var i=0
	var RepEl //reference to the element containing the html to keep
	
	//get the reference to the tbody that has the HTML to keep
	for(i==0; i< document.getElementsByTagName("tbody").length ;i++){
		if(document.getElementsByTagName("tbody")[i].innerHTML.indexOf(strFind)>0){			
			RepEl=document.getElementsByTagName("tbody")[i]
		}		
	}
	
	//add extra HTML to the HTML to keep
	bodyhtml="<div id=PFdiv name=PFDiv><table border=0 cellpadding=2 cellspacing=0><tr><td>&nbsp;</td><td>" + bodyhtml + "</td></tr></table><P></div>" 	
	
	//over write the HTML in the body and save the overwritten html for later.
	if (RepEl.parentElement){
		RG_BODY_HTML=RepEl.parentElement.outerHTML
		RepEl.parentElement.outerHTML= bodyhtml
	}else{
		RG_BODY_HTML=RepEl.parentNode.innerHTML
		RepEl.parentNode.innerHTML=bodyhtml
	}
	
}

function DrawPrintFriendlyUCHeader(){
	//replace UCNavigation
	var ucnavhtml = document.getElementById("UCNav")
	RG_UCNAV_HTML = ucnavhtml.innerHTML
	ucnavhtml.innerHTML="<br>&nbsp;<font class='PrinterHeader'> UCSF School Of Medicine</font>"
}

function DrawPrintFriendlyMedSchHeader(bread){
	//replace UCNavigation
	var mednavhtml = document.getElementById("MEDNav")
	RG_MEDNAV_HTML = mednavhtml.innerHTML
	//mednavhtml.innerHTML="MED School HEADER HEADER HEADER<P>"
	mednavhtml.innerHTML=bread
}

function DrawPrintButton(){
	if (document.getElementsByTagName){
		//document.write("<a href='' onClick='OpenPrintWindow(); return false;'><img src='/design/redesign/global/images/icon_print.gif' width='15' height='11' border=0><img src='/design/redesign/global/images/1x1_transparent.gif' width='15' height='1' border=0></a>")
	}
}
function DrawNewPrintButton(){
	var sPrntr
	if (document.getElementsByTagName){
		document.write("<a href='' onClick='OpenPrintWindow(); return false;'id='PF_ICON'><img  src='/design/redesign/global/images/icon_print.gif' width='15' height='11' alt='Print This Page' border='0' hspace='8' border=0 align='middle'></a>")
	}
}
function CheckPfOverRide(){
//checks to see if "pfoverride" is in a comment in the main content area.
//if it is then it hides the printerfriendly icon.

	var sOverrideHTML = new String(GetElementHTMLContainingString(document,"td","pfoverride"))
	//is the string PFOverride present in the doucment?
	//if so hide the pf image/icon.
	if (sOverrideHTML!='undefined'){
		document.getElementById("PF_ICON").style.display='none';
	}
}
function DrawPrintFriendlyBack(){
	return "<a href='' onClick='ReversePrinterFriendly();return false;'>Back To Normal Layout</a>"
}

function GetElementHTMLContainingString(doc,el,str){
	var i=0
	
	for(i==0; i< doc.getElementsByTagName(el).length ;i++){
		if(doc.getElementsByTagName(el)[i].innerHTML.indexOf(str)>0){			
		
			return doc.getElementsByTagName(el)[i].innerHTML
		}
	}
}

window.onLoad=LoadImages();
CheckStyleSheetCookie();