/* ==================================================================== */
/*                              Form inputs                             */
/* ==================================================================== */

/* initializeForms() 
 * Locate form field inputs on the page and initiate default events
 */
function initializeForms() {
	var i;

	// Search forms should restore their default value
	var searchinput = document.getElementById("searchinput");
	if (searchinput) {
		searchinput.onfocus=function(){clearSetField(this);};
		searchinput.onblur=function(){clearSetField(this);};
	}

	// Though it might sometimes be helpful, do not restore the
	// default value for other input fields
	var fields = document.getElementById("typo3content").getElementsByTagName("input");
	for (i in fields) {
		if (fields[i].type=="text") {
			fields[i].onfocus=function(){focusField(this);};
			fields[i].onblur=function(){blurField(this);};
		}
	}
}

/*
 * clearSetField()
 * Clears the field to simplify use when it has a default value
 * Or sets it back to the default if it is null
 *
 * @input String
 */
function clearSetField(input) {
	if (input.defaultValue==input.value) {
		input.value = "";
	}
	else if (input.value=="") {
		input.value = input.defaultValue;
	}
}

/* focusField()
 * Clears the input field, for use in main body fields
 */
function focusField(input) {
	// clear the field if it has the default value and is not a search field
	if (input.value == input.defaultValue && input.id!="searchinput") {
		input.value = "";
	}
	input.style.backgroundColor="#f8f3cc";
}
function blurField(input) {
	input.style.backgroundColor="#fff";
}

/*
 * setReferer
 * Sets the carefully-named input field with the HTTP referer.
 * To use, authors should insert a text field with the ID 'httpref'.  Unfor-
 * tunately (for them) there may be only one such field on the page to still be
 * XHTML valid.
 *
 * Note that the Id referenced might change at any time, so you probably
 * shouldn't reference this file if not using NDSU CMS.
 * 
 */
function setReferrer() {
	var ref = document.getElementById('ndsumailformhttpref');
	if (document.referrer) {
		ref.value = document.referrer;
		ref.defaultValue = document.referrer;
	// disabling the field makes the form not submit the value at all
	//	ref.disabled = true;
	}
	else {
		ref.value = 'Not available';
	}
}


/* ==================================================================== */
/*                             Text resizer                             */
/* ==================================================================== */

var currentFontSize;
var smallFont='0.7em';
var mediumFont='0.8em';
var maximumFont='0.9em';
var path="/";
var domain=document.domain;

/**
 * initializeTextSize()
 * Adds the appropriate event actions and initiates defaults
 */
function initializeTextSize() {

	getExistingFontSize();

	var panel1d = document.getElementById("panel1d");
	var panel2d = document.getElementById("panel2d");
	var panel3d = document.getElementById("panel3d");

	if (panel1d) 
		panel1d.onclick=function(){setSmallFontSize();return false;};
	if (panel2d) 
		panel2d.onclick=function(){setMedFontSize();return false;};
	if (panel3d) 
		panel3d.onclick=function(){setMaxFontSize();return false;};
}

/**
 * getExistingFontSize()
 * Find the existing size from the cookie and set text size accordingly,
 * or if null then set the default value.
 */
function getExistingFontSize() {
	
	var existingFontSize = getFontSizeCookie("fontSize");
	if (existingFontSize!=null) {
		if (existingFontSize==smallFont) {
			setSmallFontSize();
		}
		else if (existingFontSize==mediumFont) {
			setMedFontSize();			
		}
		else if (existingFontSize==maximumFont) {
			setMaxFontSize();
		}
	}
	else {
		setMedFontSize();
	}	
}

/**
 * setSmallFontSize()
 * Sets the default font size to the document's body style
 * and sets the fontSize cookie
 */
function setSmallFontSize() {
	document.body.style.fontSize=smallFont;
	setFontSizeCookie("fontSize",smallFont,null,path,domain);

	if (document.getElementById('panel1d')) {
		document.getElementById('panel1d').className = 'fontSize';
		document.getElementById('panel2d').className = '';
		document.getElementById('panel3d').className = '';
	}
}

/**
 * setMaxFontSize()
 * Selects the large font size to the document's body style
 * and sets the fontSize cookie to max
 */
function setMaxFontSize() {
	document.body.style.fontSize=maximumFont;
	setFontSizeCookie("fontSize",maximumFont,null,path,domain);

	if (document.getElementById('panel3d')) {
		document.getElementById('panel1d').className = '';
		document.getElementById('panel2d').className = '';
		document.getElementById('panel3d').className = 'fontSize';
	}
}

/**
 * setMedFontSize
 * Selects the medium font size to the document's body style
 * and sets the fontSize cookie to medium
 */
function setMedFontSize() {
	document.body.style.fontSize = mediumFont;
	setFontSizeCookie("fontSize",mediumFont,null,path,domain);

	if (document.getElementById('panel2d')) {
		document.getElementById('panel1d').className = '';
		document.getElementById('panel2d').className = 'fontSize';
		document.getElementById('panel3d').className = '';
	}
}


/** getFontSizeCookie */
function getFontSizeCookie(cookieName){
	if (document.cookie.length > 0) { 
		var startOfCookie = document.cookie.indexOf(cookieName+"="); 
		if (startOfCookie != -1) { 
			startOfCookie += cookieName.length+1;
			var endOfCookie = document.cookie.indexOf(";", startOfCookie);
			if (endOfCookie == -1) 
				endOfCookie = document.cookie.length;
				return unescape(document.cookie.substring(startOfCookie, endOfCookie)); 
			} 
	}
	return null; 
}

/** setFontSizeCookie */
function setFontSizeCookie(cookieName, cookieValue, cookieExpiredays, path, domain) {
	var ExpireDate = new Date ();
	ExpireDate.setTime(ExpireDate.getTime() + (cookieExpiredays * 24 * 3600 * 1000));
	document.cookie = cookieName + "=" + escape(cookieValue) + 
	((cookieExpiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString())
	+ ( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" );
}



/* ==================================================================== */
/*                             Table stripes                            */
/* ==================================================================== */

// Add style to every other row in tables with class="striped" within parent id
function stripeTables() {
	//var parentObject = document.getElementById("container1"); // Parent ID
	var parentObject = document.getElementById("typo3content"); // Parent ID
	var tables = getElementsByClassName(parentObject, "table", "stripeRows1");
	var tables2 = getElementsByClassName(parentObject, "table", "stripeRows2");
	tables = tables.concat(tables2);
	for (var i = 0; i < tables.length; i++) {
		var oddRow = true;
		var rows = tables[i].getElementsByTagName("tr");
		for (var j = 0; j < rows.length; j++) {
			if (oddRow == true) {
				addClass(rows[j], "odd");
				oddRow = false;
			} else {
				addClass(rows[j], "even");
				oddRow = true;
			}
		}
	}
}

/* Return array of all elements with specified class name, limited by parent object
(use "document" for full page) and html tag (use "*" for all) */
function getElementsByClassName(parentObject, tagName, className) {
	var elements = parentObject.getElementsByTagName(tagName);
	var returnElements = new Array();
	for (var i = 0; i < elements.length; i++) {
		if (hasClass(elements[i], className)) {
			returnElements.push(elements[i]);
		}
	}
	return returnElements;
}

// Check if a class is among the classes used by an element
function hasClass(element, className) {
	var regEx = new RegExp('\\b' + className + '\\b', "i")
	return element.className.match(regEx);
}

// Add class to element (preserves any existing classes)
function addClass(element, value) {
	element.className += (element.className) ? (' ' + value) : value;
}



/* ==================================================================== */
/*                            Event listeners                           */
/* ==================================================================== */

/* addEventSimple() 
   From http://www.quirksmode.org/js/eventSimple.html */
function addEventSimple(obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent('on'+evt,fn);
}

addEventSimple(window, 'load', initializeTextSize);
addEventSimple(window, 'load', initializeForms);
addEventSimple(window, 'load', stripeTables);
