/* ---------------------------------------
Feature Rotation Script 
Written by Matt on 2010-03-29
--------------------------------------- */

window.onload = start;

function start() {
	// get all feature nav items & prep links
	prepFtrNav();
	
	// run rotate feature every few seconds
		// added "if (gFtrItems.length > 1)", so the features will only rotate if there are more than one feature - JM - Apr 14, 2010
	if (gFtrItems.length > 1)
		self.setInterval("nextFtr('fitem');", 10000);
}

// preps feature nav links to call the necessary functions on click
function prepFtrNav() {
	// ensure browser supports getElementsByTagName
	if (!document.getElementsByTagName) return false;
	
	// create array of list items on the page
	var items = document.getElementsByTagName("li");
	var j	  = 0;
	gFtrItems = new Array(); // global array to hold feature items
	
	// loop through list items to find feature items
	for (var i = 0; i < items.length; i++) {
		if (items[i].className) {
			if (hasClass(items[i], 'fitem')) {
				// assign feature item to global array
				gFtrItems[j] = items[i];
				j++;
				
				// associate actions when clicking the list item's mav link (the first child element)
				items[i].firstChild.onclick = function() {
					clrActiveFtr('fitem');
					this.parentNode.className = "fitem active";
					return false;
				}
			}
		}
	}
}

// clear active feature
function clrActiveFtr(cls) {
	// loop through active feature items
	for (var i = 0; i < gFtrItems.length; i++) {
		if (hasClass(gFtrItems[i], 'active')) {
			// clear active class from matching item
			gFtrItems[i].className = cls;
		}
	}
}

// clear active feature item and set next item active
function nextFtr(cls) {  
	var x = 0;
	var i = 0;
	
	// added "&& i < gFtrItems.length" to prevent endless loop - JM - Apr 14, 2010
	while (x != 1 && i < gFtrItems.length) {
		if (hasClass(gFtrItems[i], 'active')) {
			clrActiveFtr(gFtrItems[i], 'fitem');
			if (gFtrItems.length - 1 > i) {
				gFtrItems[i + 1].className = "fitem active";
				x = 1;
			}
			else {
				gFtrItems[0].className = "fitem active";
				x = 1;
			}
		}
		i++;
	}
}

// compare classes on the element to see there is a match
function hasClass(ele, cls) {
	return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}
