/* AddEvent Function */
/* used to add event listeners to V5+ browsers. */
function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
    obj.addEventListener(evType, fn, true); 
    return true; 
 } else if (obj.attachEvent){ 
    var r = obj.attachEvent("on"+evType, fn); 
    return r; 
 } else { 
 	obj["on"+evType] = function(){ fn(); }
 } 
} 
/* AddEvent Function */

/* Get Element by TagName Function.  Useful so you don't have to pass IDs on everypage, tagName is optional */

function getElementsByClass(classname, tagName){
	var classTags = new Array();
	var inc=0
	if (!tagName) { tagName = "*";}
	var alltags=document.all? document.all : document.getElementsByTagName(tagName)
	for (var i=0; i<alltags.length; i++){
		if (alltags[i].className.indexOf(classname)!=-1) {	
			classTags[classTags.length]=alltags[i]
		}
	}
	return classTags
}



/*check for auto */
function checkAuto(value) {
	if ( isNaN(parseInt(value)) ) { //== "auto" || value == null || !value) {
		 var x = 0;
	} else {
		var x = parseInt(value);
	}
	//return parseInt(x);
	return x;
}
/* Check for auto */

/* getHeightPadding function */
function getHeightPadding(el)
{
	//var x = document.getElementById(el);
	if (window.getComputedStyle) {
		var topPady = document.defaultView.getComputedStyle(el,'').getPropertyValue("padding-top");
		//alert(el.id + ' padding-top is ' + topPady);
		//alert('I have Computed Style');
		var bottomPady = document.defaultView.getComputedStyle(el,'').getPropertyValue("padding-bottom");
		//alert(el.id + ' padding-bottom is ' + checkAuto(bottomPady));
		var topMary = document.defaultView.getComputedStyle(el,'').getPropertyValue("margin-top");
		//alert(el.id + ' margin-top is ' + checkAuto(topMary));
		var y =  (checkAuto(topPady) + checkAuto(bottomPady)) + checkAuto(topMary);
	} else if (el.currentStyle) {
		var topPady = eval('el.currentStyle.paddingTop');
		//alert(el.id + ' padding-top is ' + checkAuto(topPady));
		var bottomPady = eval('el.currentStyle.paddingBottom');
		//alert(el.id + ' padding-bottom is ' + checkAuto(bottomPady));
		var topMary = eval('el.currentStyle.marginTop');
		//alert(el.id + ' margin-top is ' + checkAuto(topMary));
		var y = (checkAuto(topPady) + checkAuto(bottomPady)) + checkAuto(topMary);
	} else {
		var y = 0;
		//alert('I just suck');
	}
	return y;
}
/* getHeightPadding function */

/* fullHeight function*/
/*Sets elements to the 100% height of their parent Tell it what element the container is what elemnt to adjust height on and what class should trigger the bhavior*/ 
function fullHeight(rowTag, cellTag, rowClass) {
	if(document.getElementsByTagName) {
		var elements = document.getElementsByTagName(rowTag);
		for(i=0; i < elements.length; i++) {
			if (elements[i].className.match(rowClass)) {
			//alert("working on " + elements[i].id); 
				var rowElement = elements[i];
				var desiredHeight = rowElement.offsetHeight;
				var cellElements = rowElement.getElementsByTagName(cellTag);
				for(e=0; e < cellElements.length; e++) {
					//alert(cellElements[e].id + ' parent is ' + cellElements[e].parentNode.id );
					if (cellElements[e].parentNode == rowElement) {
					var heightPadding = getHeightPadding(cellElements[e]);
					cellElements[e].style.height = (desiredHeight - heightPadding) + 'px';
					//alert(cellElements[e].id + ' desiredheight is ' + desiredHeight + ' padding is ' + heightPadding);
					}
				}
			}
		}
	}
}
/* fullHeight function*/


/* maxImage function */
/*mimics max-width css declaration for IE keeps very large images from blowing out the template only applied to UVaHealth right now Ideally should implement in CF not super portable right now only works in usercontent*/
function maxImage(width) {
	if (document.all&&document.getElementById) {
		var i = "";
		var theBody = document.getElementById('wrapper');
		if (theBody && theBody.className.match("maxwidth")) {
			var theUserContent = document.getElementById("usercontent");
			var theImages = theUserContent.getElementsByTagName("IMG");
			for(i=0; i < theImages.length; i++) {
				if (theImages[i].offsetWidth > width) {
					theImages[i].style.width = width + "px";
				}
			}
		}
	}
}
/* maxImage function */

/* setupLabels function */
/* Used to make labels appear as Default values in Form Fields */
function setupLabels() {
      var objLabels = document.getElementsByTagName("LABEL");
      var objField;

      for (var i = 0; i < objLabels.length; i++) {
        if ("dynamicLabel" == objLabels[i].className) {
          objField = document.getElementById(objLabels[i].htmlFor);
          addEvent(objField, "focus", focusDynamicLabel);
          addEvent(objField, "blur", blurDynamicLabel);
          objField._labelText = objLabels[i].firstChild.nodeValue;
          objField.value = objField._labelText;
        }
      }

      for (var i = 0; i < document.forms.length; i++) {
        addEvent(document.forms[i], "submit", resetLabels);
      }
    }

    function resetLabels(event) {
      var elm = getEventSrc(event);
      var objLabels = elm.getElementsByTagName("LABEL");
      var objField;

      for (var i = 0; i < objLabels.length; i++) {
        if ("dynamicLabel" == objLabels[i].className) {
          objField = document.getElementById(objLabels[i].htmlFor);
          if (objField._labelText == objField.value) {
            objField.value = "";
          }
        }
      }
    }

    function focusDynamicLabel(event) {
      var elm = getEventSrc(event);
      if (elm._labelText == elm.value) {
        elm.value = "";
      }
    }

    function blurDynamicLabel(event) {
      var elm = getEventSrc(event);
      if ("" == elm.value) {
        elm.value = elm._labelText;
      }
    }
/* setupLabels function */

/*IEsetHover Function*/
/* Lets you mimic :hover pseudo-classes in IE*/
 function IEsetHover(element) {
	 if (document.all&&document.getElementById) {
			var elements = document.getElementsByTagName(element);
			for (var i=0; i<elements.length; i++) {
				elements[i].onmouseover=function() {
					this.origClassName = this.className;
					var tempClassStr = this.className;		
					
					tempClassStr = "hover " + tempClassStr;	// add simple 'hover' class name to emulate tag:hover
					this.className = tempClassStr;
					this.mouseup = true;
					//window.status = this.className;	// only for TEST
				}
				elements[i].onmouseout=function() {
					if (this.mouseup) {
						this.className=this.origClassName;
						this.mouseup = false;
					}
					
					//window.status = this.className;  // only for TEST
				}
			}
	}
}
/*IEsetHover Function*/

/* function to set submenu arrows.  Sets class of submenu to LIs with UL as children, pass it the class to look for */
function subMenu(theClass, theTag) {
	var theMenus = getElementsByClass(theClass, theTag);
	for (var j=0; j<theMenus.length; j++) {
		var thisMenu = theMenus[j];
		if (thisMenu) {
			var listItems = thisMenu.getElementsByTagName('li');
			for (var i = 0; i < listItems.length; i++) {
				var listKids = listItems[i].childNodes;
				for (var k = 0; k < listKids.length; k++) {
					if (listKids[k].nodeName == "UL") {
						var tempClassStr = listItems[i].className; 
						tempClassStr = "submenu " + tempClassStr;
						listItems[i].className = tempClassStr;
					}
				}
			}
		}
	}
}
/* function to set submenu arrows */

/* Template Date */
function templateDate(application) {
	var theDate;
	var date = new Date();
	var day  = date.getDate();
	var weekday = date.getDay();
	var month = date.getMonth();
	var yy = date.getYear();
	var year = (yy < 1000) ? yy + 1900 : yy;
	
	var months = new Array('January','February','March',
    'April','May','June','July','August','September',
    'October','November','December');
	
	var weekdays = new Array('Sunday', 'Monday', 'Tuesday', 
	'Wednesday', 'Thursday', 'Friday', 'Saturday');
	
	if (application =="intranet") {
		theDate = weekdays[weekday] + ", " + months[month]+ " " + day +", " + year;
	} else {
		theDate = months[month]+ " " + day +", " + year;
	}
	return theDate;
}
/* Template Date */

/* popit : Creates popus as needed */
function popit(heading,body_text,winheight) {	
	var newW;
	newW = window.open("", "newW", "resizable=yes,width=400,height="+winheight);
	newW.document.writeln('<html><head><title>information</title><link rel="STYLESHEET" href="/assets/ssi/css/hsc_global.css" type="text/css"></head><body bgcolor="#FFFFFF" onBlur="timer=setTimeout(\'window.close()\',300)" ><div align="center"><h3 align="center">'+heading+'</h3></div>'+body_text+'<p align="center"><font size="2"><a href="javascript: self.close();">close this window</a></font></p></body></html>');
	newW.document.close();
	newW.focus();
}
/* popit: */


/* hspopwin: this function for opening the site-guide menu */
function hspopwin(){
   theIndex=window.open('http://www.hsc.virginia.edu/home/site-guide.html','_sitewin','toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=300,height=450');
}
/* hspopwin */

/* goto_URL: Jumps you to location based to the script */
function goto_URL(topic) {
	window.location.href = topic.options[topic.selectedIndex].value;
}
/* goto_URL */

/* new min-width emulation for blowouts */
function blowOut(id) {
	if (document.all&&document.getElementById) {
		var wrapper = document.getElementById(id);
		if (wrapper) {
			var fullwidth = 0;
			for (var i=0; i < wrapper.childNodes.length; i++) {
/*				alert("fullwidth is " + fullwidth);
				alert(wrapper.childNodes[i].id + " width is " + wrapper.childNodes[i].offsetWidth);
				alert(wrapper.childNodes[i].id + " margin is " + (wrapper.childNodes[i].offsetLeft - fullwidth));*/
				fullwidth = fullwidth + wrapper.childNodes[i].offsetWidth;
				//alert("fullwidth is " + fullwidth);
			}
/*			alert(wrapper.offsetWidth);
			alert(fullwidth);*/
			//window.status = "wrapper: " + wrapper.offsetWidth + " fullwidth: " + fullwidth;
			if (wrapper.offsetWidth < fullwidth) {
				wrapper.style.width = fullwidth + "px";
			}

		}
	
	}
}
var wrapperWidth = 0;
/*  These down here are all the events that get set on window load */
addEvent(window, 'load', function() {
		IEsetHover("li");
		maxImage(300);
		/* this (292-296) is causing IE to freeze when loading cancer-portal.cfm template */
		 blowOut('wrapper');
		 addEvent(window, 'resize', function() {
			blowOut('wrapper');
			}
		);
		//fullHeight("div", "div", "row");
		//setupLabels();
		//subMenu("sitemenu")
		//subMenu("makeSub", "ul")
		/* end of problematic code for cancer-portal.cfm */
	}
);	
/*  These are all the events that get set on window load */


/* trim functions */

function lTrim(str) { // trims leading spaces
	return str.replace( /^\s+/g, "" );
}

function rTrim(str) { // trims trailing spaces
	return str.replace( /\s+$/g, "" );
}

function trim(str) { // trims leading and trailing spaces
	str = lTrim(str);
	str = rTrim(str);
	return str;
}

function TrimString(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}
function callTool(toolName) {	
	
	switch (toolName) {
	case 'print':
	window.location.href=addParameterToCurrentURL('printfriendly=1');	
	break;
	case 'contact':
	window.location.href=addParameterToCurrentURL('toolName=dwmEmail');
	break;
	}
}
function addParameterToCurrentURL(paramString) {
	
		return getURLServer()+'?'+paramString+'&'+getURLQueryString();
	
}
function getURLServer() {
	var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
	  return strHref.substr(0,strHref.indexOf("?")).toLowerCase();
  } else {
	return strHref;  
  }
}

function getURLQueryString() {
	
  var strHref = window.location.href;
  if ( strHref.indexOf("?") > -1 ){
    return strHref.substr(strHref.indexOf("?")).toLowerCase();
  } else {
	return "";  
  }

}
