
/***********************************************************************/
/* Stylesheet Toggle
/***********************************************************************/

function setActiveStyleSheet(title) {
var i, a, main;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
a.disabled = true;
if(a.getAttribute("title") == title) a.disabled = false;
}
}
}

function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}

function getPreferredStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1
&& a.getAttribute("rel").indexOf("alt") == -1
&& a.getAttribute("title")
) return a.getAttribute("title");
}
return null;
}

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
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) return c.substring(nameEQ.length,c.length);
}
return null;
}

window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}

window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);


function applyResizeScript() {
    if(!document.getElementById) { return; }    
    var toolTextresizeNormal = document.getElementById("tool-textresize-normal");
	var toolTextresizeLarge = document.getElementById("tool-textresize-large");
	var toolTextresizeExtralarge = document.getElementById("tool-textresize-extralarge");

    if (!toolTextresizeNormal) { return; }
	if (!toolTextresizeLarge) { return; }
	if (!toolTextresizeExtralarge) { return; }
    
  
    toolTextresizeNormal.onclick = function()
        {setActiveStyleSheet('', 1); return false;}
	toolTextresizeNormal.keypress = function()
        {setActiveStyleSheet('', 1); return false;}
	toolTextresizeLarge.onclick = function()
        {setActiveStyleSheet('textsize-large');return false;}
	toolTextresizeLarge.keypress = function()
        {setActiveStyleSheet('textsize-large');return false;}
	toolTextresizeExtralarge.onclick = function()
        {setActiveStyleSheet('textsize-extralarge');return false;}
	toolTextresizeExtralarge.keypress = function()
        {setActiveStyleSheet('textsize-extralarge');return false;}
} 


/***********************************************************************/
/* Striped Tables
/***********************************************************************/

var stripe = function() {
	var tables = document.getElementsByTagName("table");	

	for(var x=0;x!=tables.length;x++){
		var table = tables[x];
		if (! table) { return; }
		
		var tbodies = table.getElementsByTagName("tbody");
				
			for (var h = 0; h < tbodies.length; h++) {
			if (tbodies[h].className == "contentframework-stripedtable"){
				var even = true;
				var trs = tbodies[h].getElementsByTagName("tr");	
				
				for (var i = 0; i < trs.length; i++) {
					
					trs[i].onmouseover=function(){
						
						this.className += " contentframework-hoveredrow"; return false
						
					}
					
					trs[i].onmouseout=function(){
					
						this.className = this.className.replace("contentframework-hoveredrow", ""); return false
						
					}
					
					if(even)
						
						trs[i].className += " contentframework-altrow";
						
										
					even = !even;
				
			}
			}
		}
	}
}


/***********************************************************************/
/* Get Element by Class
/***********************************************************************/

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].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}


/***********************************************************************/
/* Expand/Collapse
/***********************************************************************/

function toggleIcon(obj, img) {
	var el = document.getElementById(img);
	var el2 = getElementsByClass(obj);
		
	for ( i=0;i<el2.length;i++ ) {
		if (el2[i].style.display != "none" ) {
		
			el2[i].style.display = 'none';
			document.getElementById(img).src = "../_assets/images/contentframework/icon-expand.gif";
		}
		else {
		
		el2[i].style.display = '';
                document.getElementById(img).src = "../_assets/images/contentframework/icon-collapse.gif";
		}
			
	}
}

function toggleContent(obj) {
	var el2 = getElementsByClass(obj);
		
	for ( i=0;i<el2.length;i++ ) {
		if (el2[i].style.display != "none" ) {
			el2[i].style.display = 'none';
		}
		else {		
		el2[i].style.display = '';
		}
			
	}
}


/***********************************************************************/
/* Hide objects with "jshide" class
/***********************************************************************/

function hideObject() {
	var el3 = getElementsByClass("jshide");
		
	for ( i=0;i<el3.length;i++ ) {
				
		el3[i].style.display = 'none';
			
	}
}

/***********************************************************************/
/* Tab Script
/***********************************************************************/

//** Tab Content script v2.0- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)

function ddtabcontent(tabinterfaceid){
	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("li") //Get all tab links within container
	this.enabletabpersistence=true
	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array
	this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values)
	this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
}

ddtabcontent.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

ddtabcontent.setCookie=function(name, value){
	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
}

ddtabcontent.prototype={

	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers
		this.cancelautorun() //stop auto cycling of tabs (if running)
		var tabref=""
		try{
			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=this.tabs[tabid_or_position]
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tabref!="") //if a valid tab is found based on function parameter
			this.expandtab(tabref) //expand this tab
	},

	cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )
		if (dir=="next"){
			var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0
		}
		else if (dir=="prev"){
			var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1
		}
		if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function
			this.cancelautorun() //stop auto cycling of tabs (if running)
		this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])
	},

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
		this.selectedClassTarget=objstr || "link"
	},

	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to
		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref
	},

	urlparamselect:function(tabinterfaceid){
		var result=window.location.search.match(new RegExp(tabinterfaceid+"=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL
		return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
	},

	expandtab:function(tabref){
		var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand
		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		this.expandsubcontent(subcontentid)
		this.expandrevcontent(associatedrevids)
		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"
			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "primarytabs-currentpage" : ""
		}
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)
		this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array
	},

	expandsubcontent:function(subcontentid){
		for (var i=0; i<this.subcontentids.length; i++){
			var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)
			subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value
		}
	},

	expandrevcontent:function(associatedrevids){
		var allrevids=this.revcontentids
		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface
			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"
		}
	},

	setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array)
		for (var i=0; i<this.hottabspositions.length; i++){
			if (tabposition==this.hottabspositions[i]){
				this.currentTabIndex=i
				break
			}
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		this.cycleit('next', true)
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var selectedtab=-1 //Currently selected tab index (-1 meaning none)
		var selectedtabfromurl=this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index
		this.automodeperiod=automodeperiod || 0
		for (var i=0; i<this.tabs.length; i++){
			this.tabs[i].tabposition=i //remember position of tab relative to its peers
			if (this.tabs[i].getAttribute("rel")){
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)
				this.tabs[i].onclick=function(){
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
				}
				if (selectedtabfromurl==i || this.enabletabpersistence && selectedtab==-1 && parseInt(persistedtab)==i || !this.enabletabpersistence && selectedtab==-1 && this.getselectedClassTarget(this.tabs[i]).className=="selected"){
					selectedtab=i //Selected tab index, if found
				}
			}
		} //END for loop
		if (selectedtab!=-1) //if a valid default selected tab index is found
			this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class)
		else //if no valid default selected index found
			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	} //END int() function

} //END Prototype assignment


/***********************************************************************/
/* Accessible script for select forms without a submit button
/***********************************************************************/

//(c)2006 Thomas Frank, Studentlitteratur

niceSelect=function(){    
  var f=document.forms;
    for (var i=0;i<f.length;i++){          // Walks all the forms in the document.
    var e=f[i].elements;
    for(var j=0;j<e.length;j++){        // Walks all the elements in the form.
      if(e[j].type=="select-one"){      // Chooses elements that are select 
                          // box (that does not allow multiple
                          // selections).
        e[j].formnu=i;
                          // Here comes the "trick" of this 
                          // script: it redefines the 
                          // event handlers of the element.
                          
        e[j].onclick=function(){      // If the selection is made
                          // with the mouse, the it
                          // behaves like a normal selectbox
                          // menu and submits). 
          this.onchange=function(){
            f[this.formnu].submit()
          }
        };
        e[j].onblur=function(){        // This "disarms" the onblur function
                          // so that it will not submit as soon
                          // as the default option is deselected
                          // (by moving down the select list with
                          // the arrow key).
          this.onchange=function(){return true}  
        };
        e[j].onkeydown=function(e){      // When keys are pressed on the keyboard...
          if (e){theEvent = e} else {theEvent=event};
          if (theEvent.keyCode==13){    // ...only submit when 'enter' is pressed.
            if((this.onchange+"").indexOf("submit")<0){
              f[this.formnu].submit()
            }
          }
        }
      }
    }
  }
}

/***********************************************************************/
/* On Load Events
/***********************************************************************/

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

// Apply text resize script
addLoadEvent(applyResizeScript); 

// Apply table row banding/highlighting script
addLoadEvent(stripe); 

// Hide elements using JS
addLoadEvent(hideObject); 

// Load accessible select script
addLoadEvent(niceSelect); 


