// Add event handler to body when window loads
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function () {
			oldonload();
			func();
		}
	}
}

addLoadEvent(function () {
	// Code to run on page load
	Hover.init(Hover.collections);
	Rater.init();
	Popup.init();
	DocLinks.init();
});


/*-----------------------------------------+
 | Hover - Add :hover functionality for IE |
 +-----------------------------------------*/
var Hover = {
	// Create two-dimensional array of identifiers for hover effect
	// [id/class] [child nodes] [unique]
	collections : new Array(
		new Array("nav", "li", true),
		new Array("rater", "li", false),
		new Array("vendor", "tr", false)
	),
	
	// Find all elemnts specified in array (IE only)
	init : function(collections) {
		if (document.all && document.getElementById && document.getElementsByTagName) {
			for (var i = 0; i < collections.length; i++) {
				var list = collections[i];
				var name = list[0];
				var delimiter = list[1];
				var unique = list[2];
				var children = new Array();
				
				if (unique) {
					// Unique element, find by ID
					var parent = document.getElementById(name);
					
					if (parent) {
						children = parent.getElementsByTagName(delimiter);
						Hover.addBehaviors(children);
					}
				} else {
					// Not unique, find by class
					var parents = document.getElementsByTagName("*");
					
					for (var j = 0; j < parents.length; j++) {
						if (parents[j].className.indexOf(name) > -1) {
							children = parents[j].getElementsByTagName(delimiter);
							Hover.addBehaviors(children);
						}
					}
				}
			}
		}
	},
	
	// Add class of "over" to elements when mouse hovers over them, remove when mouse stops hovering
	addBehaviors : function(collection) {
		for (var j = 0; j < collection.length; j++) {
			var node = collection[j];
			
			if (node.className.indexOf("current") == -1) {
				node.onmouseover = function() { this.className += " over"; }
				node.onmouseout = function() { this.className = this.className.replace(" over", ""); }
			}
		}
	}
};

/*----------------------------------------------+
 | DocLinks - Add icon after links to documents |
 +----------------------------------------------*/
var DocLinks = {
	init : function() {
		// Find all links
		var links = document.getElementsByTagName("a");
		
		for (var i = 0; i < links.length; i++) {
			var theLink = links[i];
			var address = theLink.href.toLowerCase();
			
			// Check if link points to files with common extensions
			var matches = address.match(/\.(doc|pdf|xls|ppt)/);
			
			if (matches) {
				// Using "match" always returns two results (not sure why)
				var ext = matches[0].substr(1, 3);
				
				// Create new image and insert it
//				var newImg = document.createElement("img");
//				newImg.alt = "(" + ext.toUpperCase() + ")";
//				newImg.className = "icon";
//				newImg.src = "/hbagc-cms/masterpage/images/icon-" + ext + ".gif";
//				newImg.title = newImg.alt;
				
//				theLink.parentNode.insertBefore(newImg, theLink.nextSibling);
				
				// Make link open in new window/tab
				theLink.onclick = function () {
					window.open(this.href);
					return false;
				}
			}
		}
	}
};

/*----------------------------------+
 | Popup - Add pop-up functionality |
 +----------------------------------*/
var Popup = {
	// Initialize popup triggers
	init : function() {
		if (!document.getElementById || !document.getElementsByTagName)
			return false;
		
		// Find all anchors
		var anchors = document.getElementsByTagName("a");
		
		for (var i = 0; i < anchors.length; i++) {
			var curAnchor = anchors[i];
			
			// Only work with anchors with class "expand" or "hide"
			if (jQuery(curAnchor).hasClass("expand")) {
				curAnchor.onclick = Popup.show;
				
				if (curAnchor.parentNode.getElementsByTagName("div").length > 0) {			
					curAnchor.parentNode.getElementsByTagName("div")[0].onblur = Popup.isolate;
					curAnchor.parentNode.getElementsByTagName("div")[0].onclick = Popup.isolate;
				}
			} else if (jQuery(curAnchor).hasClass("hide")) {
				curAnchor.onclick = Popup.hide;
			}
		}
	},
	
	// Show popup
	show : function () {
		// Find and position popup based on ID(s) in class value
		var classes = this.className.split(" ");
		for (var j = 0; j < classes.length; j++) {
			if (classes[j].indexOf("popup") != -1) {
				var p = document.getElementById(classes[j]);
				if (!p) return false;
				
				// Toggle "closed" class on popup
				if (p.className.indexOf("closed") > -1) {
					var oldClass = p.className;
					var newClass = oldClass.replace(/closed/g, "");
					p.className = newClass;
				} else {
					p.className += " closed";
				}
				
				if (p.nodeName.toLowerCase() == "div") {
					/*------+
					 | DIVs |
					 +------*/
					
					// Isolate popup (pass popup and its trigger)
					Popup.isolate(p);
					
					// Add hide functionality to close button in popup
					var anchors = p.getElementsByTagName("a");
					for (var k = 0; k < anchors.length; k++) {
						if (anchors[k].className.indexOf("close") != -1) anchors[k].onclick = Popup.hide;
					}
				} else if (p.nodeName.toLowerCase() == "tr") {
					/*-----+
					 | TRs |
					 +-----*/
					
					// Replace trigger's text (expand -> hide) or vice versa
					var oldText = this.childNodes[0];
					var newText = (oldText.nodeValue.toLowerCase() == "expand") ? document.createTextNode("Hide") : document.createTextNode("Expand");
					this.replaceChild(newText, oldText)
					
					// Add "current" class to trigger's row
					this.parentNode.parentNode.parentNode.className = (p.className.indexOf("closed") == -1) ? "current" : "";
				}
			}
		}
		
		// Replace trigger's class name to change icon
		var oldClass = this.className;
		var newClass = (oldClass.indexOf("expand") > -1) ? oldClass.replace(/expand/g, "hide") : oldClass.replace(/hide/g, "expand");
		this.className = newClass;
		
		return false;
	},
	
	// Hide popup
	hide : function () {
		var par = this.parentNode.parentNode;
		
		// Add closed class back to popup container
		par.className += " closed";
		
		// Switch "hide" class back to "expand"
		var anchors = par.getElementsByTagName("a");
		for (var k = 0; k < anchors.length; k++) {
			if (anchors[k].className.indexOf("hide") != -1) {
				var oldClass = anchors[k].className;
				var newClass = oldClass.replace(/hide/g, "expand");
				anchors[k].className = newClass;
			}
		}
		
		return false;
	},
	
	// Isolate popup (close all popups except one just opened)
	isolate : function (exception) {
		var divs = document.getElementsByTagName("div");
		
		for (var i = 0; i < divs.length; i++) {
			if (exception) {
				// Isolate passed popup
				if (divs[i].className.indexOf("popup") != -1 && divs[i] != exception) {
					// Hide DIV
					divs[i].className += " closed";
					
					// Replace DIV's trigger
					var anchors = divs[i].getElementsByTagName("a");
					
					for (var j = 0; j < anchors.length; j++) {
						if (anchors[j].className.indexOf("hide") != -1) {
							var oldClass = anchors[j].className;
							var newClass = oldClass.replace(/hide/g, "expand");
							anchors[j].className = newClass;
						}
					}
					
				}
			} else {
				// Close all popups
				if (divs[i].className.indexOf("popup") != -1) {
					divs[i].className += " closed";
					
					// Replace DIV's trigger
					var anchors = divs[i].getElementsByTagName("a");
					
					for (var j = 0; j < anchors.length; j++) {
						if (anchors[j].className.indexOf("hide") != -1) {
							var oldClass = anchors[j].className;
							var newClass = oldClass.replace(/hide/g, "expand");
							anchors[j].className = newClass;
						}
					}
				}
			}
		}
	}
};


/*----------------------------------+
 | Rater - Add stickiness to raters |
 +----------------------------------*/
var Rater = {
	// Initialize all raters
	init : function() {
		var lists = document.getElementsByTagName("ol");
		
		for (var i = 0; i < lists.length; i++) {
			if (lists[i].className.indexOf("rater") != -1) {
				var theRater = lists[i];
				
				// Set "current" class based on which INPUT is checked
				var inputs = theRater.getElementsByTagName("input");
				
				for (var j = 0; j < inputs.length; j++) {
				    if (inputs[j].checked) {
				        for (var k = j; j > -1; j--)
				            inputs[j].parentNode.parentNode.className = "current";					
					    break;
					}
				}
				
				// Find all labels
				var ratings = theRater.getElementsByTagName("label");
				
				for (var j = 0; j < ratings.length; j++) {
					var theRating = ratings[j];
					
					Event.observe(theRating, "click", function() { Rater.setRating(this); });
					theRating.onmouseover = function() { Rater.highlight(this); };
					theRating.onmouseout = function() { Rater.reset(this); };
				}
			}
		}
	},
	
	// Select radio button and highlight
	setRating : function(rating) {
		// Needed because LABELs don't work in Safari
		rating.getElementsByTagName("input")[0].checked = true;
	},
	
	// Highlight all ratings up to current one
	highlight : function(rating) {
		// Get all LABELs in rater
		var siblings = rating.parentNode.parentNode.getElementsByTagName("label");
		var foundMyself = false;
		
		// Set "current" class on all ratings leading up to one being hovered
		for (var i = 0; i < siblings.length; i++) {
			if (siblings[i] === rating) foundMyself = true;
			siblings[i].parentNode.className = (!foundMyself) ? "current" : "";
			rating.parentNode.className = "current";
		}
	},
	
	// Reset rater
	reset : function(rating) {
		// Check for selected radio button. If there is one, reset highlights
		var inputs = rating.parentNode.parentNode.getElementsByTagName("input");
		var ratingChosen = false;
		var curRating = false;
		for (var i = 0; i < inputs.length; i++) {
			if (inputs[i].checked) {
				ratingChosen = true;
				var curRating = inputs[i].parentNode;
			}
		}
		
		if (ratingChosen) {
			// Reset highlights to previously selected rating
			Rater.highlight(curRating);
		} else {
			// Reset all ratings
			var siblings = rating.parentNode.parentNode.getElementsByTagName("label");
			for (var i = 0; i < siblings.length; i++) siblings[i].parentNode.className = "";
		}
	}
};


/*------------------------------------------------+
 | Google - Popup used to suggest website address |
 +------------------------------------------------*/
function searchGoogle(searchText, alertMessage) {
	if (searchText != "")
		window.open("http://www.google.com/search?hl=en&lr=&q=" + searchText + "&btnG=Search", "Google", "width=750,height=400,location=yes,resizable=yes,toolbar=yes,scrollbars=yes");
    else if (alertMessage != "")
        alert(alertMessage);
}

/*------------------------------------------------+
 | Util                                           |
 +------------------------------------------------*/
function DisableElementListByCheckBox(cb, listOfElements) {
	if (listOfElements) {
		elementArray = listOfElements.split(",")
		for(var i=0; i < elementArray.length; i++) {
            document.getElementById(elementArray[i]).disabled = !cb.checked;
		}
	}
}

