// for use with Console2 firefox extension to ouput trace info to js console.
function debug(aMsg) {
   setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
}

/*
 * awsome fuction that handles attaching events at loadtime in a cross-browser way.
 * most useful for attaching multile window.onload events thus:
 *
 *	addEvent(window, 'load', someFunction);
 *
 * from: http://www.scottandrew.com/weblog/articles/cbs-events
 */
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);
		//alert(fn+" added");return r;
	} else {
		return false;
	}
}
// IMAGE SWAP CODE FOR MAIN MENU
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_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_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];}
}

// OPEN POP-UP
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


// TO HIGHLIGHT THE CURRENT PAGE IN THE MENU 
function highlightMenu(currentPage){
	document.images[currentPage].src="../images/nav_"+currentPage+"_on.gif";
}
// to add form submission on keypress to text fields in forms with more than one text field
//takes even object as e and the form to submit as thisForm
function checkEnter(e,thisForm){ 
	var code = 0;
	if (e && e.which){
		code = e.which;
	}else{
		code = e.keyCode;
	}
	if (code==13){
		document[thisForm].submit() //submit the form
		return false;
	}else{
		return true;	
	}
}

// tabs switcher
function swap(node, name)
{
	var n = document.getElementById('current');
	
	if (n != null)
	{
		n.id = "";
	}
	
	node.parentNode.id = "current";
	
	swapContent(name);
}

function swapContent(name)
{
	var divList = document.body.getElementsByTagName("DIV");
	
	for (i = 0; i < divList.length; i++)
	{
		if (divList[i].className == "semester")
		{
			if (divList[i].id == name)
			{
				divList[i].style.display = "block";
			}
			else
			{
				divList[i].style.display = "none";
			}
		}
	}
}
function NS_toggleLayers() {
//by Ned Schwartz - toggles visibility of layer
	var i,obj,args=NS_toggleLayers.arguments;
	for(i = 0; i < args.length; i++){
		if ((obj=MM_findObj(args[i]))!=null) {
			a = obj.parentNode;//.getElementsByTagName('a');
			td = a.parentNode;
			if (obj.className) {
				if(obj.className=='accordian'){obj.className='accordianShow';a.setAttribute('id','articleActive');}
				else{obj.className='accordian';a.setAttribute('id','hiddenLayer');}
			}

		}
	}
}



// global date vars for all semester info
// to change month that a semester becomes viewable, change the month here.
var summerStart = 3;
var summerEnd = 7;
var fallStart = 8;
var fallEnd = 11;

// function to set the current semester in the course list tabs on the main page
function setCurrentSemester(month){
	//array of li tabs
	var tabs_arr = new Array();
	//contianer of the li tabs
	ul = document.getElementById("semesterTabs");
	//find the li tabs in the ul
	tabs_arr = ul.getElementsByTagName("LI");	
	
	// hide inactive tabs
	//_hideStaleSemesters(month, tabs_arr);
	// set the active tab based on the current month passed in
	if(month >= summerStart & month <= summerEnd){
		semester = "summer";
		tab = document.getElementById("summerTab").firstChild;
	} 
	else if(month >= fallStart  & month < fallEnd){
		semester = "fall";
		tab = document.getElementById("fallTab").firstChild;
	}
	else{
		semester = "winter";
		tab = document.getElementById("winterTab").firstChild;	
	}
	// call the swap() fucntion to handle setting the tab and displaying the content;
	swap(tab,semester);
}
// pass a container id (parent) and a type of element to be hidden (elemName)
// the elemName items must have ids corresponding to the semesters (summer, fall, winter ...)
function hideStaleSemesterOfferings(parent,elemName,month){
	//debug("WHAT?");
	//array of semester tabs
	var tabs_arr = new Array();
	// array of tds corresponding to the semester heads
	var td_arr = new Array();
	// semester headers
	var th_arr = new Array();
	// array of TRs
	var tr_arr = new Array();
	
	// get the rows of the semester list
	p = document.getElementById(parent);
	tr_arr = p.getElementsByTagName("TR");
	// filter out all but elemName from first row
	th_arr = tr_arr[0].getElementsByTagName(elemName);
	// filter out all but td elems from the second table row	
	td_arr = tr_arr[1].getElementsByTagName("TD");
	
	//fill the tabs_arr with semester headers and the td_arr with corresponding semester bodies.
	for(i = 0; i < th_arr.length; i++){
			if(th_arr[i].id.toLowerCase().indexOf("summer") != -1){tabs_arr[i] = th_arr[i]; /*debug("summer")*/;}
			if(th_arr[i].id.toLowerCase().indexOf("fall") != -1){tabs_arr[i] = th_arr[i]; /*debug("fall")*/;}
			if(th_arr[i].id.toLowerCase().indexOf("winter") != -1){tabs_arr[i] = th_arr[i]; /*debug("winter")*/; }
	}
/*	for(i = 0; i < tabs_arr.length; i++)
		debug(tabs_arr[i].id+" : "+td_arr[i].id);*/
		
	
	_hideStaleSemesters(month, tabs_arr, td_arr);
}
// meant to be private helper to hide  semester page elements bassed on date.
// MUST be calld from a function that creates an array of semester elements to be shown and hidden in the form:
// tabs_arr{summer,fall,winter}
function _hideStaleSemesters(month, tabs_arr, td_arr){
	
	// set the active tab based on the current month passed in
	if(month >= summerStart & month <= summerEnd){
		semester = "summer";
		// hide winter
		_hideSemester("winter",tabs_arr, td_arr);
		// hide fall
		_hideSemester("fall",tabs_arr, td_arr);
	} 
	else if(month >= fallStart  & month < fallEnd){		
		semester = "fall";
		// hide winter
		_hideSemester("winter",tabs_arr, td_arr);
		// hide summer
		_hideSemester("summer",tabs_arr, td_arr);
	}
	else{
		semester = "winter";
		// hide fall
		_hideSemester("fall",tabs_arr, td_arr);
		// hide winter
		_hideSemester("summer",tabs_arr, td_arr);
	}		
}

function _hideSemester(semester, tabs_arr, td_arr)
{
	// do we need to hide the body in the semesters offered?
	var hideBody = typeof td_arr != "undefined";
	
	for(i=0; i < tabs_arr.length; i++)
	{
		if(typeof tabs_arr[i] != "undefined" && tabs_arr[i].id.toLowerCase().indexOf(semester) != -1)
		{
			tabs_arr[i].style.display = 'none'; 
			if(hideBody)td_arr[i].style.display = 'none';
		}
	}
}

function toggleCookie(name,initVal){
	// toggles a booean cookie between true and false
	// takes the name of the cookie and a initial value to set (either true or false)
	var cookie = readCookie(name);
	
	if(cookie == null || cookie == 'undefined')
		createCookie(name,initVal)
	else{
		var cookieVal = 'true';		
		if(cookie == 'true')
			cookie= 'false';
		else
			cookie = 'true';
		createCookie(name,cookie);
	}	
}
/*------------------------------------------------------------------------------------------------------------------------*/
/*////////////////////////////////////////////////////////////////
// this is the super accordion code. It is writen as oop js.
// so instantiate a new instance of the ecAccordion by passing 
// the construct the id of an element to make into an accordion,
// set a couple of prefferences for colors and such and 
// PRESTO!

// USAGE:
// make an html element structured as so:

		<div id="myAccordionContainer">
		
			<div id="Panel1">
				<div class="head1"></div>
				<div class="body1"></div>		
			</div>
			
			<div id="Panel2">
				<div class="head2"></div>
				<div class="body2"></div>		
			</div>
			
			( . . . )
			
		</div>
		
		// (note that the ids are arbitrary and can be anything)


// instantiate an instance of the accordion in your page, passing it the id of the acccordion container div as so:

		new ecAccordion("myAccordionContainer_ID",{options});


// the options in the constructor can be left out, or can be used to customize aspects of the accordion as follows (the values shown below are the defaults):
		
		expandedBg          : '#63699c',	// color of the accordion header when it is the selected panel
		hoverBg             : '#63699c',	// color of the accordion header when the mouse is hovering over that panel
		collapsedBg         : '#6b79a5',	// the default colour of the header
		expandedTextColor   : '#ffffff',	// colour of selected panel's text.
		expandedFontWeight  : 'bold',		// font weight of selected panel's text.
		hoverTextColor      : '#ffffff',	// colour of hover panel's text.
		collapsedTextColor  : '#ced7ef',	// default colour of panel's text.
		collapsedFontWeight : 'normal',		// default font weight of panel's text.
		borderColor         : '#1f669b',	// colour of border around each panel / header
		panelHeight         : 200,			// all panels must expand to same hight; set that here (in px)
		onHideTab           : null,			// register event to fire when panel is collapsed
		onShowTab           : null,			// register event to fire when panel is shown
		multiPanelOpen		: false			// if false only one panel can be open at a time - if true many panesl can be open simultaneously*/


/////////////////////////////////////////////////////////////////*

/*
// CLASS REPRESENTING ACCORDION AND ACCORDION MANAGER
// MAINTAINS STATE, CONFIG PREFFERENCES AND MANAGES
// COLLECTION OF PANELS
*/
if(typeof Class != 'undefined'){
	ecAccordion = Class.create();
	
	ecAccordion.prototype = {
		
		initialize: function(container, options){
			this.container	= document.getElementById(container);
			this.lastExpandedTab = null;
			this. accordionTabs = new Array();
			this.setOptions(options);
			this._attachBehaviors();
			this.container.style.borderBottom = '1px solid ' + this.options.borderColor;
			
			// set the initial visual state (collapse all content panes) ...
			for ( var i=0 ; i < this.accordionTabs.length ; i++ )
			{
				this.accordionTabs[i].showCollapsed();
				this.accordionTabs[i].content.style.display = 'none';
			}		
		},
		
		/* sets prefs from constructor arguments, provides defaults in nothing specified */
		setOptions: function(options) {
			this.options = {
				expandedBg          : '#63699c',
				hoverBg             : '#63699c',
				collapsedBg         : '#6b79a5',
				expandedTextColor   : '#ffffff',
				expandedFontWeight  : 'bold',
				hoverTextColor      : '#ffffff',
				collapsedTextColor  : '#ced7ef',
				collapsedFontWeight : 'normal',
				hoverTextColor      : '#ffffff',
				borderColor         : '#1f669b',
				panelHeight         : 200,
				onHideTab           : null,
				onShowTab           : null,
				multiPanelOpen		: false		/* if false only one panel can be open at a time - if true many panesl can be open simultaneously*/
			}.extend(options || {});
		},	
	   
		/* these are the functions to show and hide tabs (duh!) */
		showTab: function(accordionTab ) {	
			accordionTab.showExpanded();
			
			if(this.lastExpandedTab != null && this.options.multiPanelOpen == false)
				this.lastExpandedTab.showCollapsed();
			
			this.lastExpandedTab = accordionTab;
		},
		hideTab: function(accordionTab) {
			accordionTab.showCollapsed();		
			this.lastExpandedTab = null;
		},
		
		_attachBehaviors: function() {
			var panels = this._getDirectChildrenByTag(this.container, 'DIV');
			for ( var i = 0 ; i < panels.length ; i++ ) {
				var tabChildren = this._getDirectChildrenByTag(panels[i],'DIV');
				if ( tabChildren.length != 2 )
				continue; // unexpected
				var tabTitleBar   = tabChildren[0];
				var tabContentBox = tabChildren[1];
				this.accordionTabs.push( new ecAccordion.Tab(this,tabTitleBar,tabContentBox) );
			}
		},
		/* helper function to get all children of a particular tag */
		_getDirectChildrenByTag: function(e, tagName) {
			var kids = new Array();
			var allKids = e.childNodes;
	
			for( var i = 0 ; i < allKids.length ; i++ )
				if ( allKids[i] && allKids[i].tagName && allKids[i].tagName == tagName )
					kids.push(allKids[i]);
			
			return kids;
		}
	
	};
	/*
	// CLASS REPRESENTING ACCORDION PANEL, CLICKABLE
	// HEADER AND SHOW/HIDE CONTENT AREA
	*/
	ecAccordion.Tab = Class.create();
	
	ecAccordion.Tab.prototype = {
	
		initialize: function(accordion, titleBar, content) {
			this.accordion = accordion;
			this.titleBar  = titleBar;
			this.content   = content;
			this._attachBehaviors();
		},
		
		/* expand and collapse functions for accordion panels */
		showCollapsed: function() {
			this.expanded 							= false;
			this.titleBar.style.backgroundColor 	= this.accordion.options.collapsedBg;
			this.titleBar.style.color           	= this.accordion.options.collapsedTextColor;
			this.titleBar.style.fontWeight      	= this.accordion.options.collapsedFontWeight;
			this.content.style.overflow				= "hidden";
			this.content.style.display				= 'none';
			this.content.style.height 				= "1px";	  
		},
		showExpanded: function() {
			this.expanded 							= true;
			this.titleBar.style.backgroundColor 	= this.accordion.options.expandedBg;
			this.titleBar.style.color           	= this.accordion.options.expandedTextColor;
			this.content.style.overflow         	= "visible";
			this.content.style.display 				= '';
			this.content.style.height 				= this.accordion.options.panelHeight + "px";
		},
		
		/* event handlers for panel headers */
		titleBarClicked: function(e) {
			this.expanded == true ? this.accordion.hideTab(this) : this.accordion.showTab(this);
		},
		hover: function(e) {
			this.titleBar.style.backgroundColor 	= this.accordion.options.hoverBg;
			this.titleBar.style.color           	= this.accordion.options.hoverTextColor;
		},
		unhover: function(e) {
			if ( this.expanded ) {
				this.titleBar.style.backgroundColor = this.accordion.options.expandedBg;
				this.titleBar.style.color           = this.accordion.options.expandedTextColor;
			}
			else {
				this.titleBar.style.backgroundColor = this.accordion.options.collapsedBg;
				this.titleBar.style.color           = this.accordion.options.collapsedTextColor;
			}
		},
	
		_attachBehaviors: function() {
			this.content.style.border 				= "1px solid " + this.accordion.options.borderColor;
			this.content.style.borderTopWidth    	= "0px";
			this.content.style.borderBottomWidth	= "0px";
			this.content.style.margin            	= "0px";
			this.titleBar.onclick     				= this.titleBarClicked.bindAsEventListener(this);
			this.titleBar.onmouseover 				= this.hover.bindAsEventListener(this);
			this.titleBar.onmouseout  				= this.unhover.bindAsEventListener(this);
		}
	
	};
}
/*////////////////////////////////////////////////////////////////
// end of accordion oop code
/////////////////////////////////////////////////////////////////*
/*------------------------------------------------------------------------------------------------------------------------*/

function adjustBar(suffix)
{
	if(isNaN(suffix))
	{
		var titleWidth = document.getElementById("theTitle").offsetWidth;
		var totalWidth = document.getElementById("theH2").offsetWidth;
		document.getElementById("theBar").style.width = (totalWidth - titleWidth- 10) + "px";

	}
	else
	{
		var titleWidth = document.getElementById("theTitle_" + suffix).offsetWidth;
		var totalWidth = document.getElementById("theH2_" + suffix).offsetWidth;
		document.getElementById("theBar_" + suffix).style.width = (totalWidth - titleWidth- 10) + "px";

	}
}